Is there any guarantee that operations on a sequential and ordered Stream are processed in encounter order?
I mean, if I have code like this:
IntStream.range(0, 5)
.map(i -> {
myFunction(i);
return i * 2;
})
.boxed()
.collect(toList());
is there a guarantee, that it will perform myFunction() calls in the encounter order of the generated range?
I found draft JavaDocs for the Stream class which explicitely states this:
For sequential stream pipelines, all operations are performed in the encounter order of the pipeline source, if the pipeline source has a defined encounter order.
but in the official JavaDocs this line was removed. It now discusses encounter order only for selected methods. The Package java.util.stream doc in the Side-effects paragraph states:
Even when a pipeline is constrained to produce a result that is consistent with the encounter order of the stream source (for example,
IntStream.range(0,5).parallel().map(x -> x*2).toArray()
must produce[0, 2, 4, 6, 8]
), no guarantees are made as to the order in which the mapper function is applied to individual elements, or in what thread any behavioral parameter is executed for a given element.
but it says nothing about sequential streams and the example is for a parallel stream (My understanding is that it's true for both sequential and parallel streams, but this is the part I'm not sure about).
On the other hand, it also states in the Ordering section:
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 executingmap(x -> x*2)
must be[2, 4, 6]
. However, if the source has no defined encounter order, then any permutation of the values[2, 4, 6]
would be a valid result.
but this time it start with "operating on the elements", but the example is about the resulting stream, so I'm not sure they are taking side-effects in account and side-effects is really what this question is about.