Learnitweb

Java Predicate.not() method

1. Introduction

In this short tutorial, we’ll discuss the not() method of Predicate Interface. This method was added in Java 11.

2. Syntax

static<T> Predicate<T> not​(Predicate<? super T> target) : This method returns a predicate that is the negation of the supplied predicate. This is accomplished by returning result of the calling target.negate().

3. Example

In this example, we’ll filter even and odd numbers from a list. We’ll use the not() method of Predicate interface.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PredicateNotExample {
    public static void main(String[] args)
    {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // creating a predicate to check even numbers
        Predicate<Integer> even = i -> i % 2 == 0;

        // creating a predicate object which
        // is negation os supplied predicate
        Predicate<Integer> odd = Predicate.not(even);

        // filtering the even number using even predicate
        List<Integer> evenNumbers
                = list.stream().filter(even).collect(
                Collectors.toList());

        // filtering the odd number using odd predicate
        List<Integer> oddNumbers
                = list.stream().filter(odd).collect(
                Collectors.toList());
        // Print the Lists
        System.out.println(evenNumbers);
        System.out.println(oddNumbers);
    }
}

Output

[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

4. Conclusion

In this short tutorial we discussed the Predicate.not() method. This is a clean way of negating a Predicate and helps in writing more readable code.