Skip to content

How to iterate and print list of Map entries by using java stream

1. The purpose of this post

This post demonstrates how to iterate and print a list of Map<String, String> entries using Java Streams.

For example, we have a list of Map<String, String> created using Vavr as follows:

MapCreation.java
Map<String,String> map1 = HashMap.of("b1","bswen1","j1","java1","w1","website1").toJavaMap();
Map<String,String> map2 = HashMap.of("b2","bswen2","j2","java2","w2","website2").toJavaMap();
Map<String,String> map3 = HashMap.of("b3","bswen3","j3","java3","w3","website3").toJavaMap();

If you are unfamiliar with how this works, you can refer to this article.

Next, we add these maps to a list:

ListCreation.java
List<Map<String,String>> maps = Arrays.asList(map1,map2,map3);

The question is: How to iterate over this list of maps using Java Streams?

2. Environments

  • Java 1.8+
  • Vavr 0.9+

3. Solution and Code

The solution involves using the flatMap method from Java Streams:

Stream20190718.java
import io.vavr.collection.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Stream20190718 {
public static void main(String[] args) {
Map<String,String> map1 = HashMap.of("b1","bswen1","j1","java1","w1","website1").toJavaMap();
Map<String,String> map2 = HashMap.of("b2","bswen2","j2","java2","w2","website2").toJavaMap();
Map<String,String> map3 = HashMap.of("b3","bswen3","j3","java3","w3","website3").toJavaMap();
List<Map<String,String>> maps = Arrays.asList(map1,map2,map3);
maps.stream()
.flatMap(m->m.entrySet().stream())
.forEach(e-> System.out.println(e.getKey()+":"+e.getValue()));
}
}

When you run the code, you will get the following output:

Output
j1:java1
w1:website1
b1:bswen1
b2:bswen2
j2:java2
w2:website2
b3:bswen3
j3:java3
w3:website3

4. How did this work?

The flatMap method is used to flatten the stream of maps into a single stream of entries. Each map’s entry set is converted into a stream, and these streams are combined into one. Finally, the forEach method is used to print each entry.

Here is a visual representation of how flatMap works: java stream flatmap

5. Summary

Iterating over a list of maps using Java Streams is straightforward with the flatMap method. This approach allows you to process nested collections efficiently and concisely. By leveraging Streams, you can write cleaner and more readable code for handling complex data structures.

Final Words + More Resources

My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!