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

1. The purpose of this post

I would demo how to iterate and print list of Map entries by using java stream.

Say, we have a list of Map<String,String> as follows, we use Vavr to build some java HashMaps as follows:

        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 don’t know why does it work, you can refer to this article.

Then we add these maps to a list:

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

Then the question: how to iterate over this list of maps using java stream?

2. Environments

  • java 1.8+
  • Vavr 0.9+

3. Solution and Code

The solution is using a flatmap:

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()));
    }
}

Run the code, we get this result:

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

4. How did this work?

You can view this picture to see how the java stream flatmap works: java stream flatmap

5. Summary

Iterate over a list of map using java stream is easy.