Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collect Stream<Map<K,V>> into Map<K,List<V>> using java 8?

I have a stream of Map<String,Double> that I want to collect into a single Map<String,List<Double>>. Does anybody have a suggestion on how to do this?

Thanks!

like image 435
Rotavator Avatar asked Jun 21 '26 08:06

Rotavator


2 Answers

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())));
like image 74
fps Avatar answered Jun 23 '26 23:06

fps


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())));
like image 33
Rotavator Avatar answered Jun 23 '26 22:06

Rotavator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!