繁体   English   中英

Java8 Streams:如何在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对象。

您可以将item转换为一对Human对象并使用SimpleEntry进行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)));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM