Retrieving elements

To retrieve elements from a Map, you can use any of the following four methods:

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.