Case 1: Given a List of Maps. Then Join the maps according to the Key
public class Test14 {
public static void main(String[] args) {
Map<String, List<Integer>> m1 = new HashMap<>();
Map<String, List<Integer>> m2 = new HashMap<>();
m1.put("a", List.of(1));
m1.put("b", List.of(2, 3));
m2.put("a", List.of(12, 115));
m2.put("b", List.of(2, 5));
m2.put("c", List.of(6));
System.out.println("map1 => " + m1);
System.out.println("map2 => " + m2);
ArrayList<Map<String, List<Integer>>> maplist = new ArrayList<Map<String, List<Integer>>>();
maplist.add(m1);
// map1 => {a=[1], b=[2, 3]}
maplist.add(m2);
// map2 => {a=[12, 115], b=[2, 5], c=[6]}
System.out.println("maplist => " + maplist);
// maplist => [{a=[1], b=[2, 3]}, {a=[12, 115], b=[2, 5], c=[6]}]
// flatmap does omitted {}
List<Entry<String, List<Integer>>> collect11 =
maplist
.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toList());
System.out.println(" collect11 => " + collect11);
// collect11 => [a=[1], b=[2, 3], a=[12, 115], b=[2, 5], c=[6]]
// That's why we will use this flatmap
Map<String, List<Integer>> map2 = maplist.stream()
.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.toMap(
//keyMapper
Map.Entry::getKey,
//valueMapper
Map.Entry::getValue,
(list_a,list_b) -> Stream.concat(list_a.stream(), list_b.stream())
.collect(Collectors.toList())
)//tomap
);
//{a=[1, 12, 115], b=[2, 3, 2, 5], c=[6]}
System.out.println("After joining the maps according the key => " + map2);
// After joining the maps according the key => {a=[1, 12, 115], b=[2, 3, 2, 5], c=[6]}
/*
OUTPUT :
After joining the maps according the key => {a=[1, 12, 115], b=[2, 3, 2, 5], c=[6]}
*/
}// main
}