I have a Stream< Map< K, V > >
and I\'m trying to merge those maps together, but preserve duplicate values in a list, so the final type would be
Use groupingBy: see the javadoc, but in your case it should be something like that:
a.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
HashMap::new,
Collectors.mapping(Map.Entry::getValue, toList())
)
);
Or:
a.map(Map::entrySet).flatMap(Set::stream)
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, toList())
)
);
This is a bit wordier than the groupingBy solution, but I just wanted to point out that it is also possible to use toMap (as you initially set out to do) by providing the merge function:
a.flatMap(map -> map.entrySet().stream()).collect(
Collectors.toMap(Map.Entry::getKey,
entry -> {
List<Integer> list = new ArrayList<>();
list.add(entry.getValue());
return list;
},
(list1, list2) -> {
list1.addAll(list2);
return list1;
}));