Java Stream Collectors.toMap 值是一个 Set

2022-01-22 00:00:00 java-8 java java-stream

我想使用 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())));

相关文章