简体   繁体   English

使用Collectors.groupingby创建一个集合的映射

[英]Use Collectors.groupingby to create a map to a set

I know how to create a Map<T, List<U>> , using Collectors.groupingBy : 我知道如何使用Collectors.groupingBy创建Map<T, List<U>>

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

How would I modify that code to create Map<Key, Set<Item>> ? 如何修改该代码以创建Map<Key, Set<Item>> Or can I not do it using stream and so have to create it manually using a for loop etc.? 或者我可以不使用stream ,所以必须使用for循环等手动创建它?

Use Collectors.toSet() as a downstream in groupingBy : 使用Collectors.toSet()作为groupingBy中的下游:

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

You have to use a downstream collector like this: 你必须使用这样的下游收集器:

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

I also like the non-stream solution sometimes: 我有时也喜欢非流解决方案:

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

If you really wanted you could exercise to do the same via compute/merge methods too 如果你真的想要你也可以通过compute/merge方法来做同样的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM