Composing Multiple filter Operations
What you'll learn: How to chain multiple filter operations to progressively narrow down stream elements with compound conditions.
The Core Idea
Rather than cramming complex logic into a single filter predicate, you can chain multiple filter calls together. Each filter in the chain further refines the stream, passing only matching elements to the next operation. This approach mirrors building increasingly specific criteria step-by-step.
Think of it like a security checkpoint with multiple stations: visitors first show ID (filter 1), then pass a metal detector (filter 2), then verify their appointment (filter 3). Only those who pass all checks proceed.
Why Compose Filters?
Readability: Breaking complex conditions into separate filters makes your intent clearer. Instead of:
stream.filter(p -> p.getAge() > 18 && p.isActive() && p.hasPermission())
You can write:
stream
.filter(p -> p.getAge() > 18)
.filter(p -> p.isActive())
.filter(p -> p.hasPermission())
Reusability: Each filter can be extracted into a named predicate and reused across different pipelines.
Conditional Logic: You can conditionally add filters based on runtime conditions, building the pipeline dynamically.
Example
List<String> names = List.of("Alice", "Bob", "Alexander", "Anna");
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.filter(name -> name.length() > 4)
.collect(Collectors.toList());
// Result: ["Alice", "Alexander", "Anna"] → ["Alice", "Alexander"]
Each filter progressively narrows the stream. Thanks to lazy evaluation and fusion, the JVM optimizes these multiple filters efficiently—there's no intermediate collection created between them.
Key Takeaway: Chaining multiple filter operations lets you build compound conditions incrementally, improving readability and maintainability while still benefiting from stream optimization.