liveBook · Manning

forEachOrdered

As explained in 100 Java Mistakes and How to Avoid Them

forEachOrdered is a Java Stream terminal operation that applies an action to elements while preserving the stream's encounter order.

forEachOrdered() applies an action from left to right according to the stream’s encounter order, including when the input stream is parallel. It is useful when an accumulator or side effect depends on processing order, but it usually removes the benefit of parallelization. section 9.5

Ordered accumulation

A hash-code accumulator can process mapped values with forEachOrdered(op), ensuring that each update follows the stream’s encounter order. The same calculation may be affected by parallel execution when an order-sensitive accumulator is applied differently. section 9.5

Use it deliberately:

  • Choose forEachOrdered() when left-to-right processing is required for a parallel or sequential input. section 9.5
  • Expect little parallel benefit for most streams; heavy upstream operations may still make parallel execution worthwhile. section 9.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the order guarantee and performance trade-off, but does not detail the terminal-operation implementation.
Examples
Uses an order-sensitive hash-code accumulator updated through an IntConsumer.
What you can do after
Apply ordered side effects or accumulation with the forEachOrdered() terminal operation.
How it connects
Connects encounter order with parallel streams, sequential streams, stateful accumulation, and the Stream API contract.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.