Does reduce on an ordered stream reduce in order?

Cogman :

I have a List of A, B, C.

C reduce A reduce B != A reduce B reduce C (however, A reduce (B reduce C) is OK).

In other words, my reduction operation is associative but not commutative.

Does java enforce on an ordered sequential stream (such as the default one from a list) that reduction will always happen according to the encounter order? That is to say, will java reorder reductions (such that B reduce A instead of A reduce B)?

(Hopefully this is clear enough).

edit to add a little demo and maybe helping to clarify

Stream.of(" cats ", " eat ", " bats ")
  .reduce("", (a, b) -> a + b); // cats eat bats

With the above, could the output ever be "bats cats eat" or "eat bats cats"? Is that guaranteed somewhere in the spec?

Andremoniy :

My previous answer was incorrect (thanks to @shmosel for correcting me).

Now I state, that according to the specification it respects the order of the elements.

Proof is very simple. The specification claims that a reduction function has to be associative.

However, associativity it self doesn't make any sense if order is not preserved. According to the mathematical definition of the associative property:

Within an expression containing two or more occurrences in a row of the same associative operator, the order in which the operations are performed does not matter as long as the sequence of the operands is not changed.

In other words, associative property doesn't imply that:

(a + b) + c = (a + c) + b

It only allows arbitrary permutation of the order in which operations are applied.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459164&siteId=1