Collect a Stream of Map to Map>

前端 未结 2 963
你的背包
你的背包 2021-01-05 08:18

I have a Stream< Map< K, V > > and I\'m trying to merge those maps together, but preserve duplicate values in a list, so the final type would be

2条回答
  •  孤街浪徒
    2021-01-05 08:52

    Use groupingBy: see the javadoc, but in your case it should be something like that:

    a.flatMap(map -> map.entrySet().stream())
     .collect(
       Collectors.groupingBy(
         Map.Entry::getKey, 
         HashMap::new, 
         Collectors.mapping(Map.Entry::getValue, toList())
       )
    );
    

    Or:

    a.map(Map::entrySet).flatMap(Set::stream)
     .collect(Collectors.groupingBy(
         Map.Entry::getKey, 
         Collectors.mapping(Map.Entry::getValue, toList())
       )
    );
    

提交回复
热议问题