title: Does Stream.sorted().forEach() work as intended?
body: <p>While working on a Java project, I came across code that looked like this:</p>
  
  <pre><code>someMap.keySet().stream().sorted().forEach(/* ... */);
  </code></pre>
  
  <p>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. <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-" rel="nofollow noreferrer">The Javadoc for Stream#forEach</a> says:</p>
  
  <blockquote>
    <p>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.</p>
  </blockquote>
  
  <p>I know that if the code were using <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#parallelStream--" rel="nofollow noreferrer"><code>.parallelStream()</code></a> instead of <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#stream--" rel="nofollow noreferrer"><code>.stream()</code></a> 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 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEachOrdered-java.util.function.Consumer-" rel="nofollow noreferrer"><code>.forEachOrdered()</code></a> instead of <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-" rel="nofollow noreferrer"><code>.forEach()</code></a> for it to be?</p>
  
  <p>EDIT: I believe that this question is not a duplicate of <a href="https://stackoverflow.com/questions/32797579/foreach-vs-foreachordered-in-java-8-stream">forEach vs forEachOrdered in Java 8 Stream</a>, 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.</p>