【发布时间】:2015-10-07 11:16:25
【问题描述】:
给定代码
List<Integer> numbers = Arrays.asList(2, 4, 3);
int sumTotal = numbers.stream().reduce(-3, (x, y) -> x + y + 3);
int multiplyTotal = numbers.stream().reduce(1, (x, y) -> x * y);
是否可以在只迭代一次流的同时执行这两个操作?
另外,请注意每个 reduce 都有不同的标识:-3 和 1。
【问题讨论】:
-
累加器函数的标识值是值“that for all
t,accumulator.apply(identity, t)is equal tot”。您应该认识到0不是x+y+3的标识值... -
identity + y + 3 = y ,你是完全正确的。 (我解决了这个问题)
标签: functional-programming java-8 reduce