Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Predicate.not(): negate a predicate in Java

`Predicate.not()` reverses a condition and returns a predicate you can pass to methods such as `Stream.filter`. It has been available since Java 11.

Version: Java SE 21

Syntax

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

Predicate.not() is a static method on java.util.function.Predicate, available since Java 11. The call Predicate.not(target) takes one predicate that can accept a value of type T. It returns a Predicate<T>, not a boolean. When you call test on the returned predicate, it gives true where the original gives false, and vice versa.

Predicate.not(target) returns the result of calling target.negate(). If you already have a predicate in a variable, you can call negate() on it directly. The static form lets you pass a method reference such as String::isBlank without first assigning it to a Predicate variable. The ! operator negates a boolean result, not the predicate itself.

Predicate.not(null) throws NullPointerException at the call. This is different from passing null to test later: not adds no null handling, so the behavior depends on the supplied predicate.

Examples

import java.util.function.Predicate;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Stream.of("Java", "", "   ", "API")
                .filter(Predicate.not(String::isBlank))
                .forEachOrdered(System.out::println);
    }
}

Result

Java
API

`String::isBlank` matches empty strings and strings containing only whitespace. With the predicate negated, `filter` keeps only `Java` and `API`, and `forEachOrdered` prints them in input order.

Related lessons

  • Java · Lesson 63 · Basic · Version: 2

Sources