Java Stream Collectors.toMap 值是一个 Set [英] Java Stream Collectors.toMap value is a Set

查看:61
本文介绍了Java Stream Collectors.toMap 值是一个 Set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Java Stream 来运行一个 POJO 列表,例如下面的列表 List<A>,并将其转换为 Map Map.

I want to use a Java Stream to run over a List of POJOs, such as the list List<A> below, and transform it into a Map Map<String, Set<String>>.

例如A类是:

class A {
    public String name;
    public String property;
}

我在下面编写了将值收集到地图中的代码Map<String, String>:

I wrote the code below that collects the values into a map Map<String, String>:

final List<A> as = new ArrayList<>();
// the list as is populated ...

// works if there are no duplicates for name
final Map<String, String> m = as.stream().collect(Collectors.toMap(x -> x.name, x -> x.property));

但是,由于可能有多个 POJO 具有相同的 name,我希望 map 的值是一个 Set.同一个键 name 的所有 property 字符串应该放在同一个集合中.

However, because there might be multiple POJOs with the same name, I want the value of the map be a Set. All property Strings for the same key name should go into the same set.

如何做到这一点?

// how do i create a stream such that all properties of the same name get into a set under the key name
final Map<String, Set<String>> m = ???

推荐答案

groupingBy 完全符合您的要求:

import static java.util.stream.Collectors.*;
...
as.stream().collect(groupingBy((x) -> x.name, mapping((x) -> x.property, toSet())));

这篇关于Java Stream Collectors.toMap 值是一个 Set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆