Understanding the filter Operation
You'll learn what the filter operation does and how it selects elements from a stream based on a condition.
What Is filter?
The filter operation is an intermediate operation that examines each element in a stream and keeps only those that satisfy a given condition. It takes a Predicate<T> (a function that returns true or false) and produces a new stream containing only the elements where the predicate returned true.
Think of filter like a bouncer at a club: each element approaches, the bouncer applies the rule (predicate), and only those who pass the test get through to the new stream. The original stream isn't modified—you get a brand-new stream with the qualifying elements.
How It Works
Because filter is an intermediate operation, it's lazy—nothing actually happens until you invoke a terminal operation. You can chain multiple filter calls together, and the stream pipeline will efficiently process elements through all filters in sequence.
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8);
Stream<Integer> evenNumbers = numbers.filter(n -> n % 2 == 0);
// Produces stream: 2, 4, 6, 8
In this example, the predicate n -> n % 2 == 0 tests each number. Only those divisible by 2 pass through to the resulting stream.
Practical Scenarios
Use filter whenever you need to narrow down data: finding active users, selecting items above a price threshold, or extracting valid records. It's one of the most common operations you'll use in stream processing.
Key Takeaway: The filter operation selects elements matching a predicate, creating a new stream with only those that pass the test—it's lazy and doesn't execute until a terminal operation triggers the pipeline.