How to iterate (loop) over the elements in a Map in Java 8

AlvinAlexander
12.8K views

Open Source Your Knowledge, Become a Contributor

If you need to iterate over the elements in a Map in Java 8, this source code shows how to do it:

This approach uses an anonymous function — also known as a lambda — and it’s similar to the approach used to traverse a Map in Scala.

How to iterate a Java 8 Map: A complete example

The following complete example shows how to iterate over all of the elements in a Java Map (or HashMap) using both a) the Java 8 style and b) the type of code you had to use prior to Java 8:

As a quick summary, if you needed to see how to iterate over the elements in a Map/HashMap in Java 8, I hope this is helpful.