Java8 Streams:如何保留 map 之前的值以供 collect/groupingBy 函数访问
Java8 Streams: How to preserve the value before map to be accessed by collect/groupingBy functions
我正在使用 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)));
我正在使用 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)));