Java Map entrySet() Method Guide
The Map interface in Java provides the entrySet() method to retrieve a collection of key-value pairs in a Map. This method returns a Set collection containing all the key-value pairs in the Map, each represented in the form of a Map.Entry object.
The general steps for using the entrySet() method are as follows:
- Fetch the Map object.
- Retrieve the collection of key-value pairs by calling the entrySet() method.
- Iterate through the key-value pairs collection and process each key-value pair sequentially.
Here is an example code:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) {
// 创建一个Map对象
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// 获取键值对集合
Set<Entry<String, Integer>> entrySet = map.entrySet();
// 遍历键值对集合
for (Entry<String, Integer> entry : entrySet) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
In the example above, we first create a HashMap object and add three key-value pairs to it. We then use the entrySet() method to get the set of key-value pairs, and iterate through this set using an iterator to print out the key and value of each pair.