Map<K,V>
can be viewed as an associative storage (i.e. a container that connects keys to their values). It can also be viewed as a collection of pairs, where the first element is the key, and the second element is its corresponding value.
The majority of methods in Map<K,V>
supports the associative container view of the map. Map.Entry<K,V>
interface is there to support the other view of the map - i.e. as a collection of key-value pairs.
Each map provides access to so called entry set, which is a set of pairs from the map. Each pair is represented by an instance of Map.Entry<K,V>
.
Map<Integer,String> myMap = ...
for (Map.Entry<Integer,String> e : myMap.entrySet()) {
System.out.println(e.getKey()+" ---> "+e.getValue());
}
One could have defined MapEntry<K,V>
interface outside Map<K,V>
. However, since the interface is very closely related to the map, a decision to nest the interface inside the map makes perfect sense.