Combining Predicates with and(), or(), and negate()
What you'll learn: How to chain Predicate instances together to build complex filtering logic using built-in default methods.
The Problem with Single Predicates
So far, you've used predicates to test single conditions—like checking if a number is positive or if a string is empty. But real-world filtering often requires multiple conditions: "Is this person an adult and a resident?" or "Is the price over budget or below minimum quality?"
Building Complex Conditions
The Predicate<T> interface provides three powerful default methods for combining predicates:
and(Predicate<T> other)
Creates a new predicate that returns true only if both predicates are true (logical AND).
Predicate<Integer> isPositive = n -> n > 0;
Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isPositiveAndEven = isPositive.and(isEven);
// Only 2 and 4 pass
List<Integer> numbers = List.of(-2, 0, 1, 2, 3, 4);
numbers.stream().filter(isPositiveAndEven).forEach(System.out::println); // 2, 4
or(Predicate<T> other)
Creates a predicate that returns true if either predicate is true (logical OR).
Predicate<String> isShort = s -> s.length() < 3;
Predicate<String> startsWithA = s -> s.startsWith("A");
Predicate<String> shortOrStartsWithA = isShort.or(startsWithA);
List<String> words = List.of("Hi", "Apple", "Banana", "An");
words.stream().filter(shortOrStartsWithA).forEach(System.out::println); // Hi, Apple, An
negate()
Creates a predicate that returns the opposite result (logical NOT).
Predicate<Integer> isPositive = n -> n > 0;
Predicate<Integer> isNotPositive = isPositive.negate();
List.of(-1, 0, 5).stream().filter(isNotPositive).forEach(System.out::println); // -1, 0
Chaining Them Together
These methods return new predicates, so you can chain them fluently for complex logic without messy nested conditions.
Key Takeaway: Use and(), or(), and negate() to compose simple predicates into sophisticated filtering logic—it's cleaner and more readable than embedding complex boolean expressions in lambdas.