Video in progress

Strong Middle 🌊 Streams and lambdas

How do forEach and forEachOrdered differ, and what does forEachOrdered "cost" in a parallel stream?

forEach doesn't guarantee order: in parallel, elements arrive in any order and from several threads at once. forEachOrdered calls in source order, one at a time. The earlier stages (map, filter) still run in parallel, but the terminal action is sequential and results are buffered.

📖 Answer

IntStream.range(0, 10).parallel().forEach(i -> System.out.print(i + " "));
// 6 5 8 9 7 2 1 0 4 3: different every time

IntStream.range(0, 10).parallel().forEachOrdered(i -> System.out.print(i + " "));
// 0 1 2 3 4 5 6 7 8 9

One subtle point: the Javadoc calls forEach "nondeterministic" even on a sequential stream. The current JDK preserves order in sequential mode, but that's not a guarantee: code that depends on order should use forEachOrdered.

How forEachOrdered works in parallel: each chunk processes its own elements, but the terminal action is invoked in turn from left to right. Even if the right-hand chunk is ready, its results wait until the left one is done. So:

  • if there's heavy computation inside map, you still benefit from parallelism, and only the last step is sequential;
  • if map is cheap and the main work is inside forEachOrdered (for example, writing to a file), there's almost no benefit from parallelism, and you pay for extra buffering.

A practical recommendation: if the result is a collection, use neither forEach nor forEachOrdered: use toList() or collect. They preserve order and are thread-safe in parallel.

The place where forEachOrdered is really needed is ordered output (a file, a socket) with heavy earlier computation:

try (var out = Files.newBufferedWriter(path)) {
    records.parallelStream()
           .map(this::renderLine)                       // heavy, parallel
           .forEachOrdered(line -> write(out, line));   // in order, on a single thread
}

Inside write you'd have to wrap the checked IOException, which is a separate topic.