Performance Characteristics of filter
What you'll learn: You'll understand why filter is both lazy and short-circuiting, which means it doesn't do unnecessary work until absolutely needed.
The Lazy Nature of filter
When you call filter() on a stream, nothing actually happens yet. The filter operation doesn't immediately check every element against your predicate. Instead, it just records that a filtering step needs to happen.
Think of it like writing a recipe rather than cooking. When you add filter(age > 18) to your stream pipeline, you're just writing down "only include adults" in your recipe. The actual checking doesn't occur until someone decides to cook—that is, when a terminal operation runs.
Short-Circuiting Behavior
The filter operation is also short-circuiting when combined with short-circuiting terminal operations. If you use findFirst() after a filter(), the stream stops evaluating predicates as soon as it finds the first match. It won't waste time testing elements that come after.
Example scenario: Imagine filtering a million-element stream and then calling findFirst(). If the first element passes the filter, the remaining 999,999 elements are never even tested. The predicate runs only once, not a million times.
Evaluates Only What's Needed
Because of laziness, filter evaluates predicates on-demand during the terminal operation. Each element flows through the entire pipeline one at a time, rather than filter processing all elements before moving to the next operation. This "element-by-element" flow is what makes streams efficient.
Key Takeaway: filter is lazy (doesn't execute until a terminal operation runs) and short-circuiting (stops testing predicates as soon as the terminal operation can finish), making it highly efficient for large or infinite streams.