Java Stream Collectors.toMap value is a Set(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Stream Collectors.toMap 值是一个 Set
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- 未找到/usr/local/lib 中的库 2022-01-01
- 获取数字的最后一位 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01