Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Predicate.negate() — negate a predicate

`negate()` returns a predicate for the same input type that reverses the original test result without changing the original predicate.

Version: Java SE 21

Syntax

default Predicate<T> negate()

Predicate<T> negated = predicate.negate();

Predicate<T> in java.util.function represents a test that takes one input of type T and returns a boolean. Predicate.negate() is a default instance method available since Java 8. It takes no arguments and returns a Predicate<T>, not a boolean.

Calling p.negate() neither changes p nor runs its test. When you later call test(value) on the returned predicate, the default implementation behaves like value -> !p.test(value): true becomes false, and false becomes true. If the original test throws an exception, the negation does not catch it.

Use p.negate() to store or pass around the opposite condition. Use !p.test(value) when you only need the inverted result for one value. The static method Predicate.not(p), available since Java 11, takes the predicate as an argument and calls its negate() method.

Examples

import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Predicate<Integer> isEven = n -> n % 2 == 0;
        Predicate<Integer> isOdd = isEven.negate();

        System.out.println(isEven.test(4) + " " + isOdd.test(4));
        System.out.println(isEven.test(7) + " " + isOdd.test(7));
    }
}

Result

true false
false true

Each line shows the result of `isEven` first and `isOdd` second. Since `4` is even and `7` is odd, the two lines show the results in opposite order.

Related lessons

  • Java · Lesson 62 · Basic · Version: 2

Sources