【发布时间】:2016-08-24 18:01:11
【问题描述】:
我有几个像下面这样的课程
class Pojo {
List<Item> items;
}
class Item {
T key1;
List<SubItem> subItems;
}
class SubItem {
V key2;
Object otherAttribute1;
}
我想根据 key1 聚合项目,对于每个聚合,子项目应按以下方式聚合 key2:
Map<T, Map<V, List<Subitem>>
Java 8 Collectors.groupingBy 嵌套如何实现这一点?
我正在尝试一些东西,但中途卡住了
pojo.getItems()
.stream()
.collect(
Collectors.groupingBy(Item::getKey1, /* How to group by here SubItem::getKey2*/)
);
注意:这与级联groupingBy 不同,后者基于与讨论here 相同的对象中的字段进行多级聚合
【问题讨论】:
-
你可以试试吗?
pojo.getItems().stream().collect(Collectors.groupingBy(Item::getKey1)).entrySet().stream() .collect(Collectors.toMap(Entry::getKey, (e)-> e.getValue().stream().map(it -> it.getSubItems().stream().collect(Collectors.groupingBy(SubItem::getKey2)))));我不确定。 -
@David Pérez Cabrera:我认为这行得通,但是将所有内容完全收集到一个临时的
Map<T, List<Item>>中可能会非常昂贵。
标签: java collections lambda java-8 java-stream