why do we use entrySet() method and use the returned set to iterate a map?

Because, logically, a map is a Set collection of key-value pairs - which is what a Map.Entry represents. Iteration is an operation on a collection generally, not a map specifically.

However, I've often wondered myself why Map doesn't implement Iterable<Map.Entry<K,V>> et al and provide an iterator() method over the map entries directly instead of requiring an entry set (which it could certainly do also to provide a full Set API.


This is as close to iterating over the map as we can because you have to say whether you want just the keys, just the values or the whole key/value entry. For Sets and Lists, there is only one option so, no need to have a separate method to do this.

BTW: This is how I would iterate over a Map. Note the use of generics, the for-each loop and the LinkedHashMap so the entries appear in some kind of logical order. TreeMap would be another good choice.

Map<K,V> m=new LinkedHashMap<K,V>();
for(Map.Entry<K,V> entry: m.entrySet())
    System.out.println(entry.getKey() + ": " + entry.getValue());

In Java 8 you can write

m.forEach((k, v) -> System.out.println(k + ": " + v));

Map is a collection of pairs of things, right (Entries). So you can iterate over entries, or iterate over the keys only (map.keySet()), or over the value only (map.values()). What else do you want to be able to iterate over?