Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Preserve encounter order with Stream.forEachOrdered

Use `forEachOrdered` when a terminal action must follow the stream’s encounter order, even in a parallel pipeline. Ordinary `forEach` does not make that guarantee in parallel mode.

Version: Java SE 21

Syntax

java.util.Collection<E>: default Stream<E> parallelStream()
java.util.stream.Stream<T>: void forEachOrdered(Consumer<? super T> action)
Contrast on java.util.stream.Stream<T>: void forEach(Consumer<? super T> action)

collection.parallelStream().forEachOrdered(action);

In Java SE 21, Collection.parallelStream() creates a stream with the collection as its source. The default implementation creates it in parallel mode, but the contract permits an implementation to return a sequential stream. Parallel mode does not guarantee multiple threads or a speedup.

Stream.forEachOrdered(action) is a terminal operation that returns void. It takes a Consumer<? super T> and runs the action for each element that reaches the end of the pipeline, following the encounter order if one is defined. For a List, that is the list’s element order, and filter preserves the relative order of the elements it keeps. A HashSet by itself defines no such order. forEachOrdered neither sorts the elements nor creates an order where none exists.

The terminal actions run one at a time: the action for one element happens-before the actions for subsequent elements. The actions need not run on the same thread, and earlier stages can still run in parallel. This guarantee applies to these action calls, not to unrelated accesses to shared state by other threads.

Ordinary Stream.forEach(action) does not guarantee encounter order in a parallel pipeline, even if a particular run happens to preserve it. Use it only when action order does not matter, and make any shared-state access safe. With either method, the action must not interfere with the stream source. Do not reuse a stream after a terminal operation; create a fresh stream for another pass.

Examples

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(5, 2, 1, 4, 3);

        numbers.parallelStream()
                .filter(n -> n % 2 != 0)
                .forEachOrdered(System.out::println);

        AtomicInteger matches = new AtomicInteger();
        numbers.parallelStream()
                .filter(n -> n % 2 != 0)
                .forEach(n -> matches.incrementAndGet());
        System.out.println("Count: " + matches.get());
    }
}

Result

5
1
3
Count: 3

The first pipeline prints the odd numbers in list order: `5`, `1`, `3`, not in ascending order. The second uses `forEach` only for contrast: it increments an atomic counter, so `Count: 3` does not depend on action order. If you only need a count, use `count()` instead of a shared counter.

Related lessons

  • Java · Lesson 43 · Advanced · Version: 2
  • Java · Lesson 57 · Intermediate · Version: 2

Sources