本文介绍了Java Stream Collectors.toMap值是一个Set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Java Stream来运行POJO列表,例如下面的列表 List< A>
,并将其转换为Map Map< String,Set< String>>
。
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具有相同的名称
,我希望地图的值为 Set
。所有属性
相同密钥名称
的字符串应该进入相同的集合。
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 does exactly what you want:
import static java.util.stream.Collectors.*;
...
as.stream().collect(groupingBy((x) -> x.name, mapping((x) -> x.property, toSet())));
这篇关于Java Stream Collectors.toMap值是一个Set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!