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


基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01