What is the usage of the negate function in Java?

In Java, the negate function is used to perform logical negation on lambda expressions. It is primarily used for function composition and conditional filtering in functional programming.

The negate function is a default method defined in the java.util.function.Predicate interface. This interface is a functional interface that takes an input parameter and returns a boolean value, commonly used for conditional statements. The negate function can perform a negation operation on the test method in the Predicate interface, returning the opposite boolean value from the original result.

Here is an example of using the negate function:

import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Predicate<Integer> isPositive = num -> num > 0;
        Predicate<Integer> isNegative = isPositive.negate();
        
        System.out.println(isPositive.test(10)); // 输出: true
        System.out.println(isNegative.test(10)); // 输出: false
    }
}

In the example above, a Predicate object named isPositive is first defined to determine if the input number is positive. Then, an isNegative Predicate object is created by calling the negate function to check if the input number is negative.

Using the negate function can easily perform logical negation operations on Lambda expressions, reducing the need for writing repetitive code.

bannerAds