What is the purpose of the entrySet method in Java?
The entrySet method in Java is used to return a collection of all key-value pairs contained in a Map. Each key-value pair is a Map.Entry object that includes a key and its corresponding value.
The return type of the entrySet method is Set
The advantage of using the entrySet method is that it can avoid combining keySet and get methods, improving the performance of the code. It also makes it more convenient to iterate and operate on key-value pairs in a Map. For example, you can iterate through all key-value pairs in a Map using the entrySet method to perform specific operations such as updating values, deleting key-value pairs, etc.
Here is an example code that demonstrates how to use the entrySet method to retrieve a set of key-value pairs from a Map, and iterate through each pair to output the key and value.
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for (Map.Entry<String, Integer> entry : entrySet) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
The output result is:
Key: A, Value: 1
Key: B, Value: 2
Key: C, Value: 3