Java Map entrySet: Retrieve Key-Value Pairs
In Java, the entrySet() method can be used to retrieve elements from a Map collection. This method will return a collection of type Set, which contains key-value pairs from the Map.
Here is an example code demonstrating how to retrieve elements in a Map collection using the entrySet() method.
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// 创建一个Map集合
Map<String, Integer> map = new HashMap<>();
// 向Map中添加元素
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// 使用entrySet()方法获取Map中的元素
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
// 遍历entrySet集合,输出键值对元素
for (Map.Entry<String, Integer> entry : entrySet) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
In the example above, a HashMap type Map collection is first created, and then several elements are added to the Map using the put() method. Next, the entrySet() method is used to retrieve the elements in the Map, and the returned Set collection is stored in the entrySet variable. Finally, a for loop is used to iterate through the entrySet collection, printing out the key and value of each key-value pair element.