00:00

Java Stream forEachOrdered() Method

Last updated:

forEachOrdered() is a terminal operation of java.util.stream.Stream, available since Java 8, that performs an action on each element in the encounter order of the stream, if the stream has a defined order. Unlike forEach(), it keeps that order even on parallel streams.

This tutorial explains what encounter order means, how forEachOrdered() combines parallel processing with ordered output, what it costs, and when it is the right choice.

1. Syntax and Method Signature

Stream.java (API)
// java.util.stream.Stream<T> (Java 8)
void forEachOrdered(Consumer<? super T> action)

// primitive versions
void IntStream.forEachOrdered(IntConsumer action)

The parameter is a Consumer, exactly as for forEach(). The specification adds two guarantees: actions run in encounter order, and each action happens-before the action for the next element, so no extra synchronisation is needed between them.

2. How forEachOrdered() Works

On a sequential stream, forEachOrdered() behaves like forEach(). On a parallel ordered stream, earlier pipeline stages such as map() still run in parallel, but results are buffered so that the action is applied to element 1, then element 2, and so on. The action itself therefore runs one element at a time, which removes part of the parallel speed-up.

If the stream has no encounter order, for example one created from a HashSet or after unordered(), there is no order to respect and the method behaves like forEach().

Parallel processing with ordered output Four invoices are processed in parallel by worker threads and finish in the order 3, 1, 4, 2. forEach would print them in that finishing order. forEachOrdered waits and prints them in encounter order 1, 2, 3, 4. PROCESSED BY FINISHED forEachOrdered PRINTS invoice 1 worker A 2nd 1st invoice 2 worker B 4th 2nd invoice 3 worker C 1st 3rd invoice 4 worker A 3rd 4th
Figure 1: The upstream work still runs in parallel, but the actions are released in encounter order. Elements that finish early wait for their predecessors.

3. Java Examples

Example 1: Same output in sequential and parallel mode (Java 9+)

Print an ordered list of receipt lines from a parallel stream.

OrderedReceipt.java
import java.util.List;

public class OrderedReceipt {

    public static void main(String[] args) {
        List<String> items = List.of("rice 2kg", "dal 1kg", "oil 1L", "salt 1kg", "tea 250g");

        items.parallelStream()
                .map(String::toUpperCase)
                .forEachOrdered(line -> System.out.println("- " + line));
    }
}
Output
- RICE 2KG
- DAL 1KG
- OIL 1L
- SALT 1KG
- TEA 250G

How it works: map() may run on several threads, but the lines are printed in list order every time. With forEach() the order would vary.

Example 2: Heavy work in parallel, ordered writing

Compute a checksum for each file block in parallel, then append the results to a report in block order.

OrderedChecksums.java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class OrderedChecksums {

    static long checksum(int block) {
        long hash = 7;
        for (int i = 0; i < 200_000; i++) {
            hash = hash * 31 + (block ^ i);
        }
        return Math.abs(hash % 10_000);
    }

    public static void main(String[] args) {
        List<String> report = new ArrayList<>();   // only touched by forEachOrdered, one element at a time

        IntStream.rangeClosed(1, 6)
                .parallel()
                .mapToObj(block -> "block-" + block + ": " + checksum(block))
                .forEachOrdered(report::add);

        report.forEach(System.out::println);
    }
}
Output
block-1: 6377
block-2: 7015
block-3: 9417
block-4: 7767
block-5: 2951
block-6: 5273

How it works: The expensive checksum() calls run in parallel, while the cheap add() calls run in order, one at a time. The happens-before guarantee makes a plain ArrayList safe here. Still, toList() would be the simpler way to build this list.

Example 3: Unordered sources have no order to keep (Java 9+)

Show that forEachOrdered() on a sorted source keeps sorted order, while on an unordered stream it cannot add order.

OrderNeedsOrderedSource.java
import java.util.List;
import java.util.TreeSet;

public class OrderNeedsOrderedSource {

    public static void main(String[] args) {
        TreeSet<String> codes = new TreeSet<>(List.of("DEL", "BOM", "MAA", "CCU"));

        System.out.print("TreeSet, parallel, forEachOrdered: ");
        codes.parallelStream().forEachOrdered(c -> System.out.print(c + " "));
        System.out.println();

        System.out.print("Explicitly sorted, parallel:       ");
        List.of("DEL", "BOM", "MAA", "CCU").parallelStream()
                .sorted()
                .forEachOrdered(c -> System.out.print(c + " "));
        System.out.println();
    }
}
Output
TreeSet, parallel, forEachOrdered: BOM CCU DEL MAA
Explicitly sorted, parallel:       BOM CCU DEL MAA

How it works: A TreeSet stream is ordered and sorted, and sorted() defines an order for the list. With a HashSet source, forEachOrdered() would follow whatever unspecified order the set has.

4. Real-World Use Cases

  • Ordered output from parallel work: render invoices or statements in parallel, then write them to a file in sequence.
  • Streaming responses: send rows to a client in the order of the query while computing them in parallel.
  • Logging: keep log lines in input order when the per-element work is parallel.

5. Important Points

  • Requires an ordered stream to mean anything; otherwise it acts like forEach().
  • Performance: waiting for earlier elements reduces parallelism; heavy work should happen in earlier stages, not in the action.
  • Happens-before: each action is visible to the next, so the action may touch non-thread-safe state.
  • Sequential streams: no difference from forEach().
  • Exceptions stop the operation; actions after the failing element are not run.

6. forEach() vs forEachOrdered()

AspectforEach()forEachOrdered()
Order of actionsNot guaranteedEncounter order, if defined
Parallel actionsRun concurrentlyRun one at a time
Thread safety needed in actionYes, for parallel streamsNo (happens-before between actions)
Speed in parallelFasterSlower, due to ordering
Use whenOrder does not matterOutput order matters

If you only need an ordered result, toList() and collect() also respect encounter order and are often simpler; see forEach().

7. Common Mistakes and Best Practices

Paying for order you do not need

If the action is, for example, saving each record independently, order is irrelevant and forEach() is faster on parallel streams.

Doing the heavy work inside the action

Slow
pages.parallelStream().forEachOrdered(page -> writer.write(render(page)));   // render() runs one at a time
Better
pages.parallelStream().map(this::render).forEachOrdered(writer::write);       // render() runs in parallel

Other mistakes to avoid

  • Expecting order from a HashSet or HashMap source. Sort first.
  • Using it just to print a sequential stream. forEach() is equivalent there.
  • Building lists with it. Use toList().

8. Summary

  • forEachOrdered() applies an action in encounter order, even on parallel streams.
  • Earlier stages still run in parallel; only the actions are serialised.
  • It needs an ordered source; on unordered streams it behaves like forEach().
  • Do heavy work before it, in map(), and use it only when output order matters.

9. References