Operation Order and Performance
What You'll Learn
You'll learn how the sequence of intermediate stream operations directly impacts performance, and how to arrange them for maximum efficiency.
Why Operation Order Matters
Think of stream operations like an assembly line. The order you place stations on that line determines how much work each station has to do. If you filter out 90% of items early, the remaining stations only process 10% of the original workload.
The Golden Rule: Filter Early, Map Late
Filter first: Reduce your dataset as soon as possible. Every element you eliminate early means less work for downstream operations.
// Less efficient: transforming everything, then filtering
stream
.map(String::toUpperCase) // Transforms ALL elements
.filter(s -> s.length() > 5); // Then filters
// More efficient: filtering first
stream
.filter(s -> s.length() > 5) // Filters FIRST
.map(String::toUpperCase); // Only transforms survivors
Minimize Expensive Operations
Place "cheap" operations (like simple predicates) before "expensive" ones (like database lookups, complex calculations, or object creation):
stream
.filter(user -> user.isActive()) // Cheap check first
.filter(user -> expensiveDatabaseLookup(user)) // Expensive check last
.map(user -> createComplexReport(user)); // Heavy transformation at end
Other Ordering Principles
- Use
distinct()after filtering but before expensive transformations - Apply
limit()as early as possible when you only need a subset - Place
sorted()late if subsequent operations reduce the stream size
Key Takeaway: Order your stream operations with this priority: filter first to shrink the dataset, apply cheap operations before expensive ones, and transform (map) as late as possible to minimize wasted computation.