[英]Modifying the returned Map value type with collectors.groupingBy in Java stream
[英]Stream groupingBy sub type
我有 2 个实体:
class Parent {
Integer id;
List<Child> children;
}
class Child {
Integer id;
Parent parent;
}
在我的数据库查询中,我正在获取Parents
的列表。 现在我想按子 ID 对这个列表进行分组,即
Map<Integer, List<Parent>> myMap;
使用 Java 8 的分组,我该怎么做?
现在我正在使用resultList.stream().collect(groupingBy(Parent::getChildren))
,但这会创建Map<Set<Child>, List<Parent>>
,这不是我想要的。
也许你会发现flatMap
在这里很有用:
Map<Integer, List<Parent>> childMap =
resultList.stream()
.flatMap(Parent::getChildren)
.collect(groupingBy(Child::getId, Collectors.mapping(Child::getParent,
Collectors.toList())));
使用flatMap
来获取孩子。 然后为孩子 ID 和父母创建 map 条目。 然后按子 ID 对 map 条目列表进行分组,并收集 map 条目组值作为列表。
Map<Integer, List<Parent>> myMap =
resultList
.stream()
.flatMap(e -> e.getChildren().stream()
.map(a -> new SimpleEntry<Integer,Parent>(a.getId(), e)))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));
或者更简化使用 Child 的构造函数
Map<Integer, List<Parent>> myMap =
resultList
.stream()
.flatMap(e -> e.getChildren().stream()
.map(a -> new Child(a.getId(), e)))
.collect(Collectors.groupingBy(Child::getId, Collectors.mapping(Child::getParent,
Collectors.toList())));
如果每个父母的每个孩子都有可用的父母数据,那么@cs95 解决方案会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.