How to collect Stream> into Map> using java 8?

前端 未结 2 1575
星月不相逢
星月不相逢 2020-12-19 21:48

I have a stream of Map that I want to collect into a single Map>. Does anybody have a suggesti

相关标签:
2条回答
  • 2020-12-19 22:41

    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())));
    
    0 讨论(0)
  • 2020-12-19 22:53

    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())));
    
    0 讨论(0)
提交回复
热议问题