BiPredicate is a functional interface introduced in JDK 8. This interface is provided in java.util.function package. BiPredicate operates on two arguments and returns a boolean based on a condition. It is a functional interface and thus can be used in lambda expression also.
BiPredicate is same as Predicate with the difference that it takes two arguments instead of one.
@FunctionalInterface
public interface BiPredicate<T, U> {
boolean test(T t, U u);
}
Methods in BiPredicate interface
| default BiPredicate<T,U> and(BiPredicate<? super T, ? super U> other) | Returns a composed predicate that represents a short-circuiting logical AND of this predicate and other. |
| default BiPredicate<T,U> negate() | Returns a predicate that represents the logical negation of this predicate. |
| default BiPredicate<T,U> or(BiPredicate<? super T, ? super U> other) | Returns a composed predicate that represents a short-circuiting logical OR of this predicate and other. |
| boolean test(T t, U u) | Evaluates this predicate on the given arguments. |
BiPredicate Example 1
In this example, we’ll use BiPredicate to compare two strings.
import java.util.function.BiPredicate;
public class BiPredicateExample {
public static void main(String[] args) {
//BiPredicate to accept and compare two strings
BiPredicate<String, String> bipredicate = (str1, str2) -> str1.equals(str2);
//call test() method to compare two strings
boolean result1 = bipredicate.test("hello", "world");
boolean result2 = bipredicate.test("hello", "hello");
//print result
System.out.println("result1: "+ result1);
System.out.println("result2: "+ result2);
}
}
Output
result1: false
result2: true
BiPredicate Example 2
import java.util.function.BiPredicate;
public class BiPredicateExample {
public static void main(String[] args) {
BiPredicate<Long, Long> biPredicate1 = (x, y) -> x > y;
BiPredicate<Long, Long> biPredicate2 = (x, y) -> x == y;
//example of and() method
System.out.println(biPredicate1.and(biPredicate2).test(9l, 8l));
// example of or() method
System.out.println(biPredicate1.or(biPredicate2).test(9l, 7l));
// example of negate() method
System.out.println(biPredicate1.negate().test(8l, 8l));
}
}
Output
false
true
true
