Java HashMap and other Map collections are not implemented Iterable interface like List or Set. However, you can iterate theirs key-value pairs, entrySet(), keySet() and values() as below
Iterate over key-value pairs
- with Java 8+
forEach(BiConsumer)ofMapinterface
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);
immutableMap.forEach((k, v) -> System.out.printf("%s=%d%s", k, v, System.lineSeparator()));
Iterate over HashMap's entrySet()
- with for-each loop
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);
for (Map.Entry<String, Integer> entry : immutableMap.entrySet()) {
System.out.println(entry);
}
- with Java 8+
forEach(Consumer)ofIterableinterface
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);
immutableMap.entrySet().forEach(System.out::println);
Iterate over HashMap's keySet()
- with for-each loop
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);
for (String key : immutableMap.keySet()) {
System.out.println(key);
}
- with Java 8+
forEach(Consumer)ofIterableinterface
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);
immutableMap.keySet().forEach(System.out::println);
Iterate over HashMap's values()
- with for-each loop
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);
for (Integer value : immutableMap.values()) {
System.out.println(value);
}
- with Java 8+
forEach(Consumer)ofIterableinterface
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);
immutableMap.values().forEach(System.out::println);
Conclusion
In this tutorial, we learned some ways to iterate over a HashMap key-value pairs, entry set, key set, and values by using the enhanced for-each loop, Java 8+ Map's forEach(BiConsumer) and Iterable's forEach(Consumer)