forEachOrdered for Parallel Streams
What you'll learn: How to process parallel stream elements in their original order using forEachOrdered.
The Challenge with Parallel Streams and Order
You've learned that forEach doesn't guarantee order when used with parallel streams—elements might be processed in whatever order threads complete their work. But what if you need the original encounter order preserved, even when processing happens in parallel?
Enter forEachOrdered
forEachOrdered is a terminal operation specifically designed to handle this scenario. It processes stream elements in their encounter order, even when the stream is parallel. Think of it like runners finishing a race at different times, but being announced in their starting-order regardless of when they crossed the finish line.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
// forEach with parallel stream - unpredictable order
numbers.parallelStream()
.forEach(n -> System.out.print(n + " "));
// Might print: 5 1 7 3 2 8 4 6
System.out.println();
// forEachOrdered with parallel stream - ordered output
numbers.parallelStream()
.forEachOrdered(n -> System.out.print(n + " "));
// Always prints: 1 2 3 4 5 6 7 8
When to Use It
Use forEachOrdered when:
- Processing happens in parallel (performance benefit)
- But side effects must occur in order (correctness requirement)
- Example: writing results to a file where order matters
The Trade-off
forEachOrdered sacrifices some parallelism benefits because threads must coordinate to maintain order. It's still potentially faster than sequential processing, but not as fast as unordered parallel forEach.
Key Takeaway: Use forEachOrdered when you need ordered side effects with parallel streams; it maintains encounter order at the cost of some parallel performance, bridging the gap between parallel execution and sequential output requirements.