What is the and() method of the BiPredicate functional interface?

Overview

BiPredicate is a functional interface that accepts two arguments and returns a boolean value.

The BiPredicate interface is defined in the java.util.function package. To import the BiPredicate interface, we will check the following import statement:

import java.util.function.BiPredicate;

and() method

The and() method is used to chain multiple implementations of the BiPredicate functional interface together as a short-circuiting logical AND operation. If any implementation returns false during the evaluation, then the subsequent implementations will not be invoked.

Syntax


default BiPredicate and(BiPredicate<? super T, ? super U> other)

Parameters

  • BiPredicate<? super T, ? super U> other: This is the BiPredicate to the chain.

Return value

This method returns a composed predicate.

Example

import java.util.function.BiPredicate;
public class Main{
public static void main(String[] args) {
BiPredicate<Integer, Integer> arg1IsEven = (arg1, arg2) -> arg1 % 2 == 0;
BiPredicate<Integer, Integer> arg2IsEven = (arg1, arg2) -> arg2 % 2 == 0;
int arg1 = 4;
int arg2 = -4;
BiPredicate<Integer, Integer> composedPredicate = arg1IsEven.and(arg2IsEven);
System.out.printf("((%s %% 2 == 0) && (%s %% 2 == 0)) = %s", arg1, arg2, composedPredicate.test(arg1, arg2));
System.out.println();
arg2 = -5;
System.out.printf("((%s %% 2 == 0) && (%s %% 2 == 0)) = %s", arg1, arg2, composedPredicate.test(arg1, arg2));
}
}

Explanation

  • Line 1: We import the relevant BiPredicate interface.
  • Line 7: We define a BiPredicate called arg1IsEven to check if the first argument is even.
  • Line 9: We define a BiPredicate called arg2IsEven to check if the second argument is even.
  • Line 11: We define the first argument called arg1.
  • Line 13: We define the second argument called arg2.
  • Line 15: We combine arg1IsEven and arg2IsEven using the and() method to get a composed BiPredicate to check if both the arguments are even.
  • Line 17: We test the composed BiPredicate using arg1 and arg2.
  • Line 20: We assign a different value to arg2.
  • Line 22: We test the composed BiPredicate using arg1 and arg2.

Free Resources