如果仅对BinaryOperator参数之一进行汇总,那么Java流实际上会减少什么?

Ily*_*iev 4 java java-stream

看一下下面的代码:在二进制运算符中,我们有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)));
Run Code Online (Sandbox Code Playgroud)

这是输出:为了向您澄清,我在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]
Run Code Online (Sandbox Code Playgroud)

那么问题是,在获得Optional [512]之前,什么样的治理才能起作用?

Zhe*_*yaM 6

因为您有10个参数,但运算为9。2 ^ 9 = 512

  • @IlyaYevlampiev认为您的减少量为`(1,1)-> 1 + 1 ...(2,1)-> 2 + 2 ....(256,1)-> 256 + 256` (2认同)
  • @IlyaYevlampiev`y`代表流的下一个元素,其中`x`代表旧的归约结果。因此,就您而言-是的,请忽略 (2认同)