Java8 Streams:如何保留collect/groupingBy函数访问的map之前的值



我使用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对象。

您可以使用SimpleEntryitem转换为一对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)));

最新更新