使用Collectors.groupingby创建到集合的地图

时间:2019-02-25 09:45:01

标签: java set java-stream grouping

我知道如何使用Map<T, List<U>>创建Collectors.groupingBy

Map<Key, List<Item>> listMap = items.stream().collect(Collectors.groupingBy(s->s.key));

我将如何修改该代码以创建Map<Key, Set<Item>>?还是我不能使用stream做它,所以必须使用for循环等手动创建它?

3 个答案:

答案 0 :(得分:13)

Collectors.toSet()用作groupingBy的下游:

Map<Key, Set<Item>> map = items.stream()
            .collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));

答案 1 :(得分:5)

您必须像这样使用下游收集器:

Map<Key, Set<Item>> listMap = items.stream()
    .collect(Collectors.groupingBy(s -> s.key, Collectors.toSet()));

答案 2 :(得分:4)

有时我也喜欢非流式解决方案:

 Map<Key, Set<Item>> yourMap = new HashMap<>();
 items.forEach(x -> yourMap.computeIfAbsent(x.getKey(), ignoreMe -> new HashSet<>()).add(x));

如果您确实希望,也可以通过compute/merge方法进行锻炼