Filtering with Complex Predicates
You'll learn how to combine multiple conditions in a single filter operation using logical operators to create sophisticated element selection rules.
The Core Idea
So far you've used simple predicates in filter() — checking one condition at a time. But real-world filtering often requires multiple criteria simultaneously. Java's logical operators (&&, ||, and !) let you combine conditions within a single predicate, creating complex predicates that evaluate multiple rules in one pass.
Combining Conditions
Think of complex predicates like airport security: you might need both a valid ticket and proper ID (&&), or you might accept either a passport or a driver's license (||). Similarly, stream filters can check multiple properties of each element:
// Simple predicate: one condition
stream.filter(person -> person.getAge() >= 18)
// Complex predicate: multiple conditions with AND
stream.filter(person -> person.getAge() >= 18 && person.hasLicense())
// Complex predicate: multiple conditions with OR
stream.filter(product -> product.isOnSale() || product.getPrice() < 50.0)
// Negation with NOT
stream.filter(order -> !order.isCancelled() && order.getTotal() > 100)
// Three conditions combined
stream.filter(employee ->
employee.getDepartment().equals("Engineering") &&
employee.getYearsOfService() > 5 &&
employee.getSalary() < 100000)
The predicate function returns true only when the entire logical expression evaluates to true, following standard Java boolean logic.
Why Use Complex Predicates?
Combining conditions in one filter is more efficient than chaining multiple filter() calls — it evaluates all conditions for each element in a single pass through the stream.
Key Takeaway: Use logical operators (&&, ||, !) inside filter predicates to combine multiple conditions, enabling sophisticated multi-criteria filtering in a single, efficient operation.