Junior
What is the purpose of the BiPredicate<T, U> functional interface in Java?
sobes.tech AI
Answer from AI
BiPredicate<T, U> is a functional interface representing a predicate that takes two arguments of types T and U and returns a boolean value. It is used to test whether a pair of objects satisfies a certain condition.
Main methods:
boolean test(T t, U u): Performs the test on the given arguments.default BiPredicate<T, U> and(BiPredicate<? super T, ? super U> other): Returns a composite predicate representing the logical AND of this predicate and another.default BiPredicate<T, U> or(BiPredicate<? super T, ? super U> other): Returns a composite predicate representing the logical OR of this predicate and another.default BiPredicate<T, U> negate(): Returns a predicate representing the logical negation of this predicate.
Example usage:
import java.util.function.BiPredicate;
public class BiPredicateExample {
public static void main(String[] args) {
BiPredicate<String, Integer> lengthCheck = (str, len) -> str.length() == len;
System.out.println(lengthCheck.test("Hello", 5)); // true
System.out.println(lengthCheck.test("World", 3)); // false
BiPredicate<String, Integer> startsWithH = (str, len) -> str.startsWith("H");
BiPredicate<String, Integer> combinedPredicate = lengthCheck.and(startsWithH);
System.out.println(combinedPredicate.test("Hello", 5)); // true
System.out.println(combinedPredicate.test("World", 5)); // false
}
}