Fusion: Combining Multiple Operations
You'll learn how the JVM optimizes chained stream operations into a single efficient pass over your data.
What Is Stream Fusion?
When you chain multiple intermediate operations together—like filter().map().filter()—you might imagine the stream processing each element through the first operation, then passing all results to the second operation, and so on. That would mean multiple passes over the data.
But the Streams API is smarter than that. Through fusion, the JVM combines consecutive operations into a single pass. Each element flows through the entire pipeline before the next element is processed, rather than processing all elements through one stage at a time.
How Fusion Works
Think of it like an assembly line where workers stand side-by-side. Instead of Worker 1 processing all 1000 items before passing them to Worker 2, each item moves through Worker 1, immediately to Worker 2, then Worker 3—one at a time. This is far more efficient.
Stream.of("apple", "banana", "apricot", "blueberry")
.filter(s -> s.startsWith("a")) // operation 1
.map(String::toUpperCase) // operation 2
.filter(s -> s.length() > 5) // operation 3
.forEach(System.out::println);
The JVM fuses these three intermediate operations. For "apple": check starts with "a" → uppercase → check length > 5 → pass to forEach. Then "banana" goes through the same fused pipeline. No intermediate collections are created between stages.
Why This Matters
Fusion eliminates the overhead of creating temporary collections between operations. You get the readability of chained operations with the performance of hand-optimized loops.
Key Takeaway: The JVM automatically fuses consecutive stream operations into a single pass over the data, giving you both clean code and optimal performance without intermediate storage overhead.