Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does actually Java stream reduce if only one of BinaryOperator argument is got summarized with itself?

Take a look onto the code below: here in binary operator we have reduce((x,y)->x+x). Why it is actually calculated to Optional[512]? I have no explanation.

System.out.println((Stream.generate(()->1d).limit(10).
            peek((doubleValue)->{
                System.out.println("Call the first peek: "+doubleValue);
            }).
            reduce((x,y)->x+x)));

And here is the output: just to clarify to you I show the individual x are 1.0 in peek section.

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]

So the question, what governs reduce to work until Optional[512] will be obtained?

like image 721
Ilya Yevlampiev Avatar asked Jan 02 '23 04:01

Ilya Yevlampiev


1 Answers

Because you have 10 arguments, but operations is 9. 2^9 = 512

like image 79
ZhenyaM Avatar answered Jan 14 '23 12:01

ZhenyaM