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

前端 未结 2 1590
星月不相逢
星月不相逢 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> result = streamOfMaps
        .flatMap(map -> map.entrySet().stream())
        .collect(Collectors.groupingBy(
            Map.Entry::getKey, 
            Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
    

提交回复
热议问题