Java流收集器。toMap值是一个集合
我想使用Java流运行POJO列表,例如下面的列表List<A>
,并将其转换为映射Map<String, Set<String>>
例如,A类是:
class A {
public String name;
public String property;
}
我编写了下面的代码,将值收集到映射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
,所以我希望映射的值是aSet
。同一个键name
的所有property
字符串都应该进入同一个集合
如何做到这一点
// 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 = ???
# 1 楼答案
相同但不同
# 2 楼答案
此外,还可以使用收集器的合并功能选项。toMap函数 收藏家。toMap(键映射器、值映射器、合并函数)如下所示:
# 3 楼答案
@Nevay的答案使用
groupingBy
肯定是正确的,但也可以通过toMap
添加mergeFunction作为第三个参数来实现:这段代码将数组映射到一个映射,其中键为
x.name
,值为HashSet
,值为x.property
。当存在重复的键/值时,将调用第三个参数合并函数来合并两个哈希集如果使用Apache公共库,也可以使用它们的
SetUtils::union
作为合并# 4 楼答案
groupingBy正是您想要的: