Java Stream forEachOrdered() Method
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
// 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().
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.
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));
}
}
- 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.
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);
}
}
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.
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();
}
}
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()
| Aspect | forEach() | forEachOrdered() |
|---|---|---|
| Order of actions | Not guaranteed | Encounter order, if defined |
| Parallel actions | Run concurrently | Run one at a time |
| Thread safety needed in action | Yes, for parallel streams | No (happens-before between actions) |
| Speed in parallel | Faster | Slower, due to ordering |
| Use when | Order does not matter | Output 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
pages.parallelStream().forEachOrdered(page -> writer.write(render(page))); // render() runs one at a time
pages.parallelStream().map(this::render).forEachOrdered(writer::write); // render() runs in parallel
Other mistakes to avoid
- Expecting order from a
HashSetorHashMapsource. 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
Frequently Asked Questions (FAQ)
Q1. What is the difference between forEach() and forEachOrdered()?
forEach() does not guarantee encounter order and in parallel streams runs actions concurrently. forEachOrdered() runs the action for each element in encounter order, one at a time, even on parallel streams.
Q2. Is forEachOrdered() slower than forEach()?
On parallel streams, yes: actions must wait for earlier elements, which reduces parallelism. On sequential streams there is no practical difference.
Q3. Does forEachOrdered() make a parallel stream sequential?
No. Earlier stages such as map() and filter() still run in parallel. Only the final actions are applied in order, one at a time.
Q4. What happens with forEachOrdered() on a HashSet?
A HashSet stream has no encounter order, so there is no order to preserve. The method then behaves like forEach().
Q5. Is forEachOrdered() thread-safe?
The specification guarantees that the action for one element happens-before the action for the next, so the action does not need extra synchronisation for state it shares only with itself.