When you use Stream.of() the doc says:
Returns a sequential ordered stream whose elements are the specified values.
So at this point, you know you have a ordered sequential stream, and the javadoc of stream ops also says:
For sequential streams, the presence or absence of an encounter order does not affect performance, only determinism. If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results.
Regarding only to the reduce
operation, the result should be identical when the order exists for sequential streams, and even for parallel ordered streams the operation will keep the final order (at least in the current implementations of java8 and java9, in the future some optimizations can occur, but the order of ordered streams using reduce
will probably never change).
You have to be carefull of knowing when the stream is ordered. For instance, operations like map
or filter
preserves the order of the stream, so if you have an ordered stream, you can use this methods and the stream will continue to be ordered.
note: ordered is totally different than sorted.
If a stream is ordered, most operations are constrained to operate on the elements in their encounter order; if the source of a stream is a List containing [1, 2, 3], then the result of executing map(x -> x*2) must be [2, 4, 6]
Edit (according to the comment):
But is not constrained to execute sequentially.
This is why the associativity is necessary, for instance, if you have a stream generated from an array like this { a
, b
, c
, d
}, then a
+ b
could be resolved first, then c
+ d
and finally all together (a
+ b
) + (c
+ d
), that's why the operation must be associative. This way if the operation is indeed associative (like it has to be) the final order will be preserved.