Stream.reduce always preserving order on parallel, unordered stream
First of all unordered
does not imply an actual shuffling; all it does it sets a flag for the Stream pipeline - that could later be leveraged.
A shuffle of the source elements could potentially be much more expensive then the operations on the stream pipeline themselves, so the implementation might choose not to do this(like in this case).
At the moment (tested and looked at the sources) of jdk-8
and jdk-9
- reduce
does not take that into account. Notice that this could very well change in a future build or release.
Also when you say unordered
- you actually mean that you don't care about that order and the stream returning the same result is not a violation of that rule.
For example notice this question/answer that explains that findFirst
for example (just another terminal operation) changed to take unordered
into consideration in java-9 as opposed to java-8.
To help explain this, I am going to reduce the scope of this string to ABCD
.
The parallel stream will divide the string into two pieces: AB
and CD
. When we go to combine these later, the result of the AB
side will be the first argument passed into the function, while the result of the CD
side will be the second argument passed into the function. This is regardless of which of the two actually finishes first.
The unordered
operator will affect some operations on a stream, such as a limit
operation, it does not affect a simple reduce
.