Collect a Stream of Map to Map>

前端 未结 2 964
你的背包
你的背包 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())
       )
    );
    
    0 讨论(0)
  • 2021-01-05 08:58

    This is a bit wordier than the groupingBy solution, but I just wanted to point out that it is also possible to use toMap (as you initially set out to do) by providing the merge function:

        a.flatMap(map -> map.entrySet().stream()).collect(
            Collectors.toMap(Map.Entry::getKey,
                    entry -> { 
                        List<Integer> list = new ArrayList<>();
                        list.add(entry.getValue());
                        return list;
                    },
                    (list1, list2) -> {
                        list1.addAll(list2);
                        return list1;
                    }));
    
    0 讨论(0)
提交回复
热议问题