Course contentsShow
← Java
Lesson 1647 of 2,87035. Functional InterfacesFree lesson

BiPredicate for Two-Argument Conditions

Explore BiPredicate<T,U> for testing conditions on two inputs, useful for comparing pairs or validating relationships.

BiPredicate for Two-Argument Conditions

What you'll learn: How to use BiPredicate<T,U> to test conditions involving two inputs instead of one.

The Two-Input Problem

You've mastered Predicate<T> for testing single values, but what happens when your condition needs to examine two arguments? Enter BiPredicate<T,U> — the two-argument cousin of Predicate.

Think of it like a comparison operator: while Predicate asks "Is this valid?", BiPredicate asks "How do these two things relate?" It's perfect for comparing pairs, validating relationships, or any scenario where your decision depends on two separate inputs.

Core Interface

BiPredicate<T,U> declares one abstract method:

boolean test(T t, U u)

Notice it takes two parameters (possibly of different types) and returns a boolean, just like Predicate.test() but with an extra argument.

Common Use Cases

Comparing pairs:

BiPredicate<Integer, Integer> isGreater = (a, b) -> a > b;
System.out.println(isGreater.test(5, 3)); // true

Validating relationships:

BiPredicate<String, Integer> hasLength = (str, len) -> str.length() == len;
System.out.println(hasLength.test("hello", 5)); // true

Different types:

BiPredicate<Person, Integer> isOlderThan = (person, age) -> person.getAge() > age;

Logical Combinations

Like Predicate, you can chain BiPredicate instances using and(), or(), and negate():

BiPredicate<String, String> bothNotEmpty = 
    (s1, s2) -> !s1.isEmpty() && !s2.isEmpty();
BiPredicate<String, String> haveSameLength = 
    (s1, s2) -> s1.length() == s2.length();

BiPredicate<String, String> combined = bothNotEmpty.and(haveSameLength);

Key Takeaway: BiPredicate<T,U> extends predicate logic to two-argument scenarios, making it ideal for comparisons, relationship validation, and any condition requiring two inputs.