Is ordered guaranteed for foreach operation? According to doc:
void forEach(Consumer<? super T> action)
Performs an action for each element of this stream.
This is a terminal operation.
The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.
Parameters:
So I understand that line //4 shall also be replaced with forEachOrdered ?
The JavaDoc API description implies that it is non-deterministic for parallel streams. If you have a sequential stream, as in the code given in the question, then forEach will process in order.
Since, the API for Stream is used for all kinds of streams, you cannot know whether a stream reference that you have received points to sequential or a parallel stream. That is why the JavaDoc says that it is non-deterministic.
However, in this case, we are creating a sequential stream and so we know that forEach will process elements in order.
If you like our products and services, please help us by posting your review here.
The [above pipeline] uses the method forEachOrdered, which processes the elements of the stream in the order specified by its source, regardless of whether you executed the stream in serial or parallel. Note that you may lose the benefits of parallelism if you use operations like forEachOrdered with parallel streams.
The above output seems to contradict the statement in the doc about the pipeline and the answer to this question. I would expect the output to be ordered, but it is not. Am I missing something?