What is the purpose of the entrySet method in Java?

In Java, the entrySet() method is used to return a Set view containing all key-value pairs in the map. Each key-value pair is represented as a Map.Entry object, which includes the key and its corresponding value.

The entrySet() method allows for easy traversal and manipulation of key-value pairs in a map. For example, you can use entrySet() to iterate through all key-value pairs in a map, or use getValue() to retrieve the value corresponding to a specific key.

Here is an example code showing how to iterate and print all key-value pairs in a map using the entrySet() method:

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) {
    System.out.println(entry.getKey() + " --> " + entry.getValue());
}

The output results in:

A --> 1
B --> 2
C --> 3

By using the entrySet() method, you can easily manipulate and handle key-value pairs in a map without needing to separately handle keys and values.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds