I have a stream of Map
that I want to collect into a single Map
. Does anybody have a suggesti
First you need to flatten your stream of maps into a stream of map entries. Then, use Collectors.groupingBy along with Collectors.mapping:
Map<String,List<Double>> result = streamOfMaps
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
Say i had:
Stream<Map<String, Double>> mapStream
Then the answer is:
mapStream.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));