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)
ofMap
interface
Iterate over HashMap
's entrySet()
- with for-each loop
- with Java 8+
forEach(Consumer)
ofIterable
interface
Iterate over HashMap
's keySet()
- with for-each loop
- with Java 8+
forEach(Consumer)
ofIterable
interface
Iterate over HashMap
's values()
- with for-each loop
- with Java 8+
forEach(Consumer)
ofIterable
interface
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)