我有两个实体:
class Parent {
Integer id;
List<Child> children;
}
class Child {
Integer id;
Parent parent;
}在我的DB查询中,我获取了一个Parents列表。现在,我想按子I对此列表进行分组,即
Map<Integer, List<Parent>> myMap;使用Java8的分组方式我该怎么做?
现在我使用的是resultList.stream().collect(groupingBy(Parent::getChildren)),但这会创建Map<Set<Child>, List<Parent>>,这并不是我想要的。
发布于 2020-06-09 04:25:37
也许你会发现flatMap在这里很有用:
Map<Integer, List<Parent>> childMap =
resultList.stream()
.flatMap(Parent::getChildren)
.collect(groupingBy(Child::getId, Collectors.mapping(Child::getParent,
Collectors.toList())));发布于 2020-06-09 04:25:45
使用flatMap获取子项。然后为子id和父id创建映射条目。然后按子id分组映射条目列表,并将映射条目组值收集为列表。
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解决方案更好。
https://stackoverflow.com/questions/62270496
复制相似问题