Java Language Maps Iterating through the contents of a Map

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any Java Language Question?