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

99封情书 提交于 2020-07-14 06:44:55

问题


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!


回答1:


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())));



回答2:


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())));


来源:https://stackoverflow.com/questions/49661952/how-to-collect-streammapk-v-into-mapk-listv-using-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!