A 减少将所有元素减少为单个值。使用减少函数(a,b) -> b
form 会将所有元素减少到最后一个,所以当你想要得到一个时,它是不合适的List
包含所有(匹配的)元素。
除此之外,您正在对输入值进行修改,这违反了该操作的约定。进一步注意,该函数需要是联想性的, 是。流是否会执行并不重要f(f(e₁,e₂),e₃))
or 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
,但由于其有状态的性质,它需要一个内部类:
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
loop.