How to negate a BiPredicate functional interface
BiPredicate is a functional interface which 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’ll check the following import statement:
import java.util.function.BiPredicate;
The negate() method
The negate() method is used to return a BiPredicate, which is a negation of the given BiPredicate.
Syntax
default BiPredicate negate()
Parameters
This method has no parameters.
Return value
This method returns a predicate.
Code
import java.util.function.BiPredicate;public class Main{public static void main(String[] args) {BiPredicate<Integer, Integer> zeroSum = (arg1, arg2) -> arg1 + arg2 == 0;int arg1 = 5;int arg2 = -4;BiPredicate<Integer, Integer> notZeroSum = zeroSum.negate();System.out.printf("(%s + %s != 0) is %s\n", arg1, arg2, notZeroSum.test(arg1, arg2));arg2 = -5;System.out.printf("(%s + %s != 0) is %s", arg1, arg2, notZeroSum.test(arg1, arg2));}}
Explanation
- Line 1: We import the relevant
BiPredicateinterface. - Line 7: We define a
BiPredicatecalledzeroSumto check if the sum of the arguments equals zero. - Line 9: We define the first argument called
arg1. - Line 11: We define the second argument called
arg2. - Line 13: We get a
BiPredicateto check if the sum of the arguments is not equal to zero by negating thezeroSumBiPredicate. - Line 15: We test the negated
BiPredicateusingarg1andarg2. - Line 17: We assign a different value to
arg2. - Line 19: We test the composed
BiPredicateusingarg1andarg2.