看看下面的代码:在二进制运算符中,我们有reduce((x,y)-> x + x)。为什么实际上计算为Optional [512]?我没有解释。
System.out.println((Stream.generate(()->1d).limit(10).
peek((doubleValue)->{
System.out.println("Call the first peek: "+doubleValue);
}).
reduce((x,y)->x+x)));
这是输出:为了向您澄清,我在peek部分显示单个x为1.0。
Call the first peek: 1.0
Call the first peek: 1.0
Call the first peek: 1.0
Call the first peek: 1.0
Call the first peek: 1.0
Call the first peek: 1.0
Call the first peek: 1.0
Call the first peek: 1.0
Call the first peek: 1.0
Call the first peek: 1.0
Optional[512.0]
那么问题是,在获得Optional [512]之前,什么样的治理才能起作用?
答案 0 :(得分:6)
因为您有10个参数,但运算为9。2 ^ 9 = 512
答案 1 :(得分:2)
从技术上讲,当您这样做时,Stream reduce并不能提供一致的操作。
担保仅与关联的归约运算一起提供,而您则没有(担保第一个操作数,而忽略第二个操作数)。
在测试代码时,您正在观察结果。
当试图就非并行流中如何实现缩减进行有根据的猜测时,这些结果丝毫不令人惊讶。但是,Stream的文档绝对不能保证这些结果,因为您不遵守要求。
例如,结果可能是1或2。尽管有些令人困惑,但仍然有意义,而您就是不满足要求的人。
答案 2 :(得分:1)
让我们看看这里发生了什么:
System.out.println((Stream.generate(()->1d).limit(10).
reduce((x,y)-> {
double ret = x+x;
System.out.println(ret);
return ret;
})));
输出为
2.0
4.0
8.0
16.0
32.0
64.0
128.0
256.0
512.0
Optional[512.0]
因为您的流中有10个参数提供给reduce,且其默认起始值为0
。
因为您使用的是(x, y) -> x+x
,实际上您将结果翻倍了9倍,成为result <- result + result
的9倍,其中@ZhenyaM提到了result <- 0 + 1
:2^9 = 512
>