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

AlvinAlexander
1,497 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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

1
9
10
11
12
13
14
15
16
17
// {...}
Map<String, String> map = new HashMap<String, String>();
map.put("first_name", "Alvin");
map.put("last_name", "Alexander");
// java 8
map.forEach((k,v)->System.out.println("key: " + k + ", value: " + v));
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("first_name", "Alvin");
map.put("last_name", "Alexander");
// java 8
map.forEach((k,v)->System.out.println("key: " + k + ", value: " + v));
// prior to java 8
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

The author of this article is Alvin Alexander, the original article can be found on https://alvinalexander.com.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content