Iterating through the contents of a Map

suggest change

Maps provide methods which let you access the keys, values, or key-value pairs of the map as collections. You can iterate through these collections. Given the following map for example:

Map<String, Integer> repMap = new HashMap<>();
repMap.put("Jon Skeet", 927_654);
repMap.put("BalusC", 708_826);
repMap.put("Darin Dimitrov", 715_567);

Iterating through map keys:

for (String key : repMap.keySet()) {
    System.out.println(key);
}

Prints:

Darin Dimitrov Jon Skeet BalusC

keySet() provides the keys of the map as a Set. Set is used as the keys cannot contain duplicate values. Iterating through the set yields each key in turn. HashMaps are not ordered, so in this example the keys may be returned in any order.

Iterating through map values:

for (Integer value : repMap.values()) {
    System.out.println(value);
}

Prints:

715567 927654 708826

values() returns the values of the map as a Collection. Iterating through the collection yields each value in turn. Again, the values may be returned in any order.

Iterating through keys and values together

for (Map.Entry<String, Integer> entry : repMap.entrySet()) {
    System.out.printf("%s = %d\n", entry.getKey(), entry.getValue());
}

Prints:

Darin Dimitrov = 715567 Jon Skeet = 927654 BalusC = 708826

entrySet() returns a collection of Map.Entry objects. Map.Entry gives access to the key and value for each entry.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Maps:
* Maps
* Iterating through the contents of a Map

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap