在使用之前的元素值对每个元素执行操作后,使用 Java 8 Stream Reduce 到 return 列表

Using Java 8 Stream Reduce to return List after performing operation on each element using previous elements values

我是 Streams 和 Reduce 的新手,所以我正在尝试并遇到问题:

我有一个计数器列表,其中包含开始计数器和结束计数器。一个项目的开始计数器总是前一个的结束计数器。我有这些计数器的列表 listItems,我想有效地循环它,过滤掉不活动的记录,然后将列表缩减为一个新列表,其中设置了所有 StartCounters。我有以下代码:

List<CounterChain> active = listItems.stream()
                .filter(e -> e.getCounterStatus() == CounterStatus.ACTIVE)
                .reduce(new ArrayList<CounterChain>(), (a,b) -> { b.setStartCounter(a.getEndCounter()); return b; });

但它并没有真正起作用,我有点卡住了,谁能给我一些建议来帮助我完成这项工作?还是有同样有效的更好方法来做到这一点?谢谢!

A Reduction 将所有元素缩减为一个值。使用 (a,b) -> b 形式的缩减函数会将所有元素缩减到最后一个,因此当您想要获得包含所有(匹配)元素的 List 时,它是不合适的。

除此之外,您正在对输入值进行修改,这违反了该操作的约定。进一步注意,该函数需要 associative,即在处理三个后续流元素时,流是否执行 f(f(e₁,e₂),e₃))f(e₁,f(e₂,e₃)) 无关紧要与你的减少功能。

或者,简而言之,您没有使用正确的工具来完成这项工作。

最干净的解决方案是不要混合这些不相关的操作:

List<CounterChain> active = listItems.stream()
    .filter(e -> e.getCounterStatus() == CounterStatus.ACTIVE)
    .collect(Collectors.toList());
for(int ix=1, num=active.size(); ix<num; ix++)
    active.get(ix).setStartCounter(active.get(ix-1).getEndCounter());

第二个循环也可以使用 forEach 实现,但由于其状态性质,它需要一个内部 class:

active.forEach(new Consumer<CounterChain>() {
    CounterChain last;
    public void accept(CounterChain next) {
        if(last!=null) next.setStartCounter(last.getEndCounter());
        last = next;
    }
});

或者,使用基于索引的流:

IntStream.range(1, active.size())
    .forEach(ix -> active.get(ix).setStartCounter(active.get(ix-1).getEndCounter()));

但与普通 for 循环相比,两者都没有太大优势。

虽然@Holger 提供的简单 for 循环的解决方案已经足够好了,但我还是建议您尝试使用第三方库来解决此类常见问题。例如:StreamEx 或 JOOL。这是 StreamEx 的解决方案。

StreamEx.of(listItems).filter(e -> e.getCounterStatus() == CounterStatus.ACTIVE)
        .scanLeft((a,b) -> { b.setStartCounter(a.getEndCounter()); return b; });