Interface Map

The Map interface has many methods similar to the methods of List and Set:

The Map interface, however, does not extend IterableCollection, or any other interface for that matter. It is designed to be able to store values by their keys. Each key is unique, while several equal values can be stored with different keys in the same map. The combination of key and value constitutes an Entry, which is an internal interface of Map. Both value and key objects must implement equals() method. A key object must also implement hashCode() method. 

Many methods of Map interface have exactly the same signature and functionality as in the interfaces List and Set, so we are not going to repeat them here. We will only walk through the Map-specific methods:

The following Map methods are much too complicated for the scope of this book, so we just mention them for the sake of completeness. They allow combining or calculating multiple values and aggregating them in a single existing value in the Map or creating a new one:

This last group of computing and merging methods is rarely used. The most popular by far are the V put(K key, V value) and V get(Object key) methods, which allow the use of the main Map function of storing key-value pairs and retrieving the value using the key. The Set<K> keySet() method is often used for iterating over the map's key-value pairs, although the entrySet() method seems a more natural way of doing that. Here is an example:

Map<Integer, String> map = Map.of(1, "s1", 2, "s2", 3, "s3");

for(Integer key: map.keySet()){
System.out.print(key + ", " + map.get(key) + ", ");
//prints: 3, s3, 2, s2, 1, s1,
}
for(Map.Entry e: map.entrySet()){
System.out.print(e.getKey() + ", " + e.getValue() + ", ");
//prints: 2, s2, 3, s3, 1, s1,
}

The first of the for loops in the preceding code example uses the more widespread way to access the key-pair values of a map by iterating over the keys. The second for loop iterates over the set of entries, which in our opinion is a more natural way to do it. Notice that the printed out values are not in the same order we have put them in the map. That is because, since Java 9, the unmodifiable collections (that is what of() factory methods produce) have added randomization of the order of Set elements. It changes the order of the elements between different code executions. Such a design was done to make sure a programmer does not rely on a certain order of Set elements, which is not guaranteed for a set.