java 11 introduced not a method to existing interface Predicate

It returns a predicate that is the negation of a given predicate.

This used to check not conditional values in java streams and list process.

Before java11, We want to filter the list of strings based on conditional predicate

We used isBlank in filter method to filter non-blank strings.

package java11;

import java.util.List;
import java.util.stream.Collectors;

public class PredicateTest {
    public static void main(String[] args) {
        List<String> numbers = List.of("one", "two", "three", "four", "five", "animal");

        List<String> list1 = numbers.stream()
                .filter(item -> !item.isBlank())
                .collect(Collectors.toList());
        list1.forEach(item -> System.out.println(item));


    }
}

Let’s see Predicate not method with example

Here is a syntax

    static <T> Predicate<T> not(Predicate<? super T> target)

Argument: predicate Returns: Predicate

To create a predicate, First, create a condition and add to it

Here is an example to remove empty strings from a List of Strings in java.

package java11;

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

public class PredicateTest {
    public static void main(String[] args) {
        List<String> numbers = Arrays.asList("one","two", "", "three");

        List<String> list = numbers.stream()
                .filter(Predicate.not(String::isBlank))
                .collect(Collectors.toList());
        list.forEach(item -> System.out.println(item));

    }
}

Output:

one
two
three

Here is an example to remove the one of the elements based on the condition

package java11;

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

public class PredicateTest {
    public static void main(String[] args) {
        List<String> numbers = List.of("one", "two", "three", "four", "five","animal");
        Predicate<String> notNumber= item->!item.equals("animal");

        List<String> list1 = numbers.stream()
                .filter(notNumber)
                .collect(Collectors.toList());
        list1.forEach(item -> System.out.println(item));

        List<String> list2 = numbers.stream()
                .filter(Predicate.not(notNumber))
                .collect(Collectors.toList());
        list2.forEach(item -> System.out.println(item));

    }
}

Output:

one
two
three
four
five
animal