Order Guarantees with forEach
What You'll Learn
You'll learn that forEach behaves differently on sequential versus parallel streams when it comes to maintaining element order.
The Order Question
When you use forEach on a stream, you might assume it always processes elements in the order they appear. That's partially true—but it depends on whether your stream is sequential or parallel.
Sequential Streams: Order Is Maintained
With sequential streams, forEach respects the encounter order of the stream. If your source collection has a defined order (like a List), forEach will process elements in exactly that order:
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
.forEach(System.out::println);
// Output: Alice, Bob, Charlie (always in this order)
Parallel Streams: Order Is Not Guaranteed
When you use parallel(), forEach prioritizes performance over order. The Stream API splits the work across multiple threads, and elements may be processed in any order:
List<String> names = List.of("Alice", "Bob", "Charlie");
names.parallelStream()
.forEach(System.out::println);
// Output: Charlie, Alice, Bob (unpredictable order)
The Analogy
Think of sequential streams as a single-file line at a coffee shop—everyone is served in order. Parallel streams are like opening multiple registers—customers get served faster, but not necessarily in the order they arrived.
When Order Matters in Parallel Streams
If you need order preservation even with parallel streams, use forEachOrdered (which you'll learn about soon) instead of forEach.
Key Takeaway: forEach maintains encounter order on sequential streams but makes no guarantees on parallel streams, where performance takes priority over ordering.