Java8 group a list of lists to map(Java8分组要映射的列表列表)
问题描述
我有一个 Model
和一个具有以下签名的 Property
类:
I have a Model
and a Property
class with the following signatures:
public class Property {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Model {
private List<Property> properties = new ArrayList<>();
public List<Property> getProperties() {
return properties;
}
}
我想要 List<Model>
中的 Map<String, Set<Model>>
,其中键是 Property<中的名称/代码>类.如何使用 java8 流按其
Propery
es 名称对该列表进行分组?所有 Property
的名称都是唯一的.
I want a Map<String, Set<Model>>
from a List<Model>
where the key would be the name from the Property
class. How can I can I use java8 streams to group that list by its Propery
es' name? All Property
es are unique by name.
可以在单个流中解决,还是应该以某种方式拆分它还是采用经典解决方案?
It is possible to solve in a single stream or should I split it somehow or go for the classical solution?
推荐答案
yourModels.stream()
.flatMap(model -> model.getProperties().stream()
.map(property -> new AbstractMap.SimpleEntry<>(model, property.getName())))
.collect(Collectors.groupingBy(
Entry::getValue,
Collectors.mapping(
Entry::getKey,
Collectors.toSet())));
这篇关于Java8分组要映射的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java8分组要映射的列表列表


- Eclipse 的最佳 XML 编辑器 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01