Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to negate a BiPredicate functional interface

abhilash

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));

    }
}
Implementation of the negate() method

Explanation

  • Line 1: We import the relevant BiPredicate interface.
  • Line 7: We define a BiPredicate called zeroSum to 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 BiPredicate to check if the sum of the arguments is not equal to zero by negating the zeroSum BiPredicate.
  • Line 15: We test the negated BiPredicate using arg1 and arg2.
  • Line 17: We assign a different value to arg2.
  • Line 19: We test the composed BiPredicate using arg1 and arg2.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring