This post would demo 5 ways to iterate a Map in java.
The 5 ways include:
traverse map using map.keySet iterator
traverse map using map.values iterator
traverse map using map.entrySet iterator
traverse map using java 8 lambda
traverse map using java stream of EntrySet
1. Environments
Java 1.8
2. Example codes
2.1 Setup a utility method to build a Map
2.2 traverse map using map.keySet iterator
2.3 traverse map using map.values iterator
Notice this method can only print values of the Map.
2.4 traverse map using map.entrySet iterator
2.5 traverse map using java 8 lambda
2.6 traverse map using java stream of EntrySet
2.7 test the 5 methods
Run the code, we got the result:
3. summary
As you can see, the traverseMap4 is the most concise one.
In this post we demoed how to iterate a Map by using various methods.You can find the whole code examples on github project, the class source code is located at this
You can find detail documents about the java stream here: