我使用Java8 Streams在列表中迭代,对于每个元素,我调用map
,然后我需要聚合结果。我的问题是,当我调用groupingBy
时,在调用map
之前,我还需要访问原始对象。以下是一个片段:
list.stream() //
.filter(item -> item.getType() == HUMAN) //
.map(item -> manager.itemToHuman(item.getId())) //
.filter(Objects::nonNull) //
.collect(Collectors.groupingBy(Human::getAge, Collectors.summarizingLong(item.getCount())));
问题出在对Collectors.summarizingLong(item.getCount())
的调用上,因为此时item
不可访问。有没有一种优雅的方法可以克服这一点?
完成map()
流转换为Stream<Human>
后,您不能在收集器中使用item
对象。
您可以使用SimpleEntry
将item
转换为一对Human
对象和count
,然后在收集器上使用它。
list.stream()
.filter(item -> item.getType() == HUMAN)
.map(item ->
new AbstractMap.SimpleEntry<>(manager.itemToHuman(item.getId()), item.getCount()))
.filter(entry -> Objects.nonNull(entry.getKey()))
.collect(Collectors.groupingBy(entry -> entry.getKey().getAge(),
Collectors.summarizingLong(Map.Entry::getValue)));