Iterating through the contents of a Map
suggest changeMaps 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);
}
println writes one key per line. One possible HashMap order is:
Darin Dimitrov
Jon Skeet
BalusC
keySet() provides the keys of the map as a Set. A set is used because the map cannot contain duplicate keys. Iterating through the set yields each key in turn. HashMap is not ordered, so the keys may be returned in any order.
Iterating through map values:
for (Integer value : repMap.values()) {
System.out.println(value);
}
println writes one value per line. One possible order is:
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());
}
printf writes one entry per line. One possible order is:
Darin Dimitrov = 715567
Jon Skeet = 927654
BalusC = 708826
entrySet() returns a set of Map.Entry objects. Map.Entry gives access to the key and value for each entry. The order is not fixed for a HashMap.