BiPredicate Composition: and, or, negate
What You'll Learn
You'll learn how to combine multiple BiPredicate instances using logical operators to build complex two-argument conditions from simpler building blocks.
The Core Idea
Just like you combined Predicate instances using and(), or(), and negate(), you can do the same with BiPredicate<T, U>. This lets you construct sophisticated two-argument boolean tests by composing simpler predicates, making your code more modular and readable.
Think of it like building with LEGO blocks: each small BiPredicate is a simple test, and the composition methods let you snap them together to create more complex logic without writing messy nested conditionals.
The Three Composition Methods
and() - Both Must Be True
Combines two BiPredicate instances where both must return true:
BiPredicate<String, Integer> isLongEnough = (s, n) -> s.length() >= n;
BiPredicate<String, Integer> startsWithA = (s, n) -> s.startsWith("A");
BiPredicate<String, Integer> combined = isLongEnough.and(startsWithA);
combined.test("Apple", 3); // true (length >= 3 AND starts with A)
combined.test("Ant", 5); // false (fails length test)
or() - Either Can Be True
Combines two BiPredicate instances where at least one must return true:
BiPredicate<Integer, Integer> sumPositive = (a, b) -> a + b > 0;
BiPredicate<Integer, Integer> bothEven = (a, b) -> a % 2 == 0 && b % 2 == 0;
BiPredicate<Integer, Integer> either = sumPositive.or(bothEven);
either.test(-5, 3); // false (sum is -2, not both even)
either.test(2, 4); // true (both even)
negate() - Flip the Result
Inverts the boolean result:
BiPredicate<String, String> areEqual = String::equals;
BiPredicate<String, String> notEqual = areEqual.negate();
notEqual.test("cat", "dog"); // true
Key Takeaway: Use and(), or(), and negate() on BiPredicate to compose complex two-argument conditions from simple, reusable predicates—just like you did with single-argument Predicate.