While working on a Java project, I came across code that looked like this:
someMap.keySet().stream().sorted().forEach(/* ... */);
The intention here is clearly to do something for each key in the map, according to the keys' natural order, and this does seem to be what happens in practice. However, I'm not sure if this behavior is guaranteed. The Javadoc for Stream#forEach says:
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.
I know that if the code were using .parallelStream()
instead of .stream()
that it wouldn't be guaranteed to work, but since it is using a sequential stream (which the Javadoc doesn't say anything about), I'm not sure. Is this guaranteed to always work, or would that code need to be using .forEachOrdered()
instead of .forEach()
for it to be?
EDIT: I believe that this question is not a duplicate of forEach vs forEachOrdered in Java 8 Stream, because that question is asking "what's an example of a difference between forEach and forEachOrdered in general", and the accepted answer is basically "parallel streams". This question is specifically about sequential streams.