To retrieve elements from a Map, you can use any of the following four methods:
- V get(Object K): It returns the value by the provided key, or null if the provided key is not in the map
- V getOrDefault(K, V): It returns the value by the provided key, or the provided (default) value if the provided key is not in the map
- Map.Entry<K,V> entry(K,V): A static method that converts the provided key-value pair into an immutable object of Map.Entry (immutable means it can be read, but cannot be changed)
- Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries): It creates an immutable map based on the provided entries
The following code demonstrates these methods:
Map<Integer, String> map = new HashMap<>();
map.put(1, null);
map.put(2, "s2");
map.put(3, "s3");
System.out.println(map.get(2)); //prints: s2
System.out.println(map.getOrDefault(2, "s4")); //prints: s2
System.out.println(map.getOrDefault(4, "s4")); //prints: s4
Map.Entry<Integer, String> entry = Map.entry(42, "s42");
System.out.println(entry); //prints: 42=s42
Map<Integer, String> entries =
Map.ofEntries(entry, Map.entry(43, "s43"));
System.out.println(entries); //prints: {42=s42, 43=s43}
And it is always possible to retrieve elements of a map by iterating, as we have described in the subsection Iterate and stream.