BiPredicate<T, U>: Two-Argument Boolean Tests
What you'll learn: How to test conditions involving two separate inputs and return a boolean result using the BiPredicate functional interface.
The Core Idea
While Predicate<T> tests a single input, sometimes you need to evaluate conditions that depend on two inputs. That's where BiPredicate<T, U> comes in. It's a functional interface with a single abstract method test(T t, U u) that takes two arguments and returns a boolean.
Think of it like a gatekeeper checking two credentials at once—both must satisfy your custom rule before proceeding.
The test Method
The BiPredicate interface defines:
boolean test(T t, U u)
You provide both arguments, and it evaluates your condition:
BiPredicate<String, Integer> isLengthGreaterThan =
(str, minLength) -> str.length() > minLength;
boolean result = isLengthGreaterThan.test("Hello", 3); // true
Common Use Cases
Comparing two values:
BiPredicate<Integer, Integer> isGreater = (a, b) -> a > b;
isGreater.test(10, 5); // true
Checking relationships between objects:
BiPredicate<String, String> startsWith = (text, prefix) -> text.startsWith(prefix);
startsWith.test("Java", "Ja"); // true
Validation with context:
BiPredicate<Double, Double> isWithinBudget =
(price, budget) -> price <= budget;
isWithinBudget.test(49.99, 50.00); // true
Combining BiPredicates
Just like Predicate, you can chain conditions using and(), or(), and negate():
BiPredicate<String, Integer> isLongEnough = (s, len) -> s.length() >= len;
BiPredicate<String, Integer> notTooLong = (s, len) -> s.length() <= len * 2;
BiPredicate<String, Integer> isValidLength = isLongEnough.and(notTooLong);
Key Takeaway: BiPredicate<T, U> extends boolean testing to scenarios requiring two inputs, using the test(T, U) method to evaluate conditions involving paired values.