Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series — Extended Java Programming Java Tutorial Module 18 - Modern Java Features 8 to 21

Java 11 Predicate.not Method for Negating Predicates

Reviewed & accurate
AI Summary

Introduction

Java 11 shipped in September 2018 with a small but beloved addition to the java.util.function package: the static method Predicate.not. Since Java 8, the Predicate interface already had an instance method called negate() that returned a logical NOT of the receiver, but the resulting code was noisy when you wanted to negate a method reference. A statement like list.removeIf(Predicate.isEqual("").negate()) reads backwards compared to the natural English form, and writing list.removeIf(s -> !s.isEmpty()) abandons the method-reference style entirely. The Java 11 predicate not method, proposed as JEP 323 and delivered under bug JDK-8150415, gives developers a clean static counterpart that reads in the same direction as the code writes: Predicate.not(String::isEmpty).

For a Java learner, java 11 predicate not is the gateway to writing fluent filter pipelines without losing the method-reference style. It also signals a broader theme of late-2010s Java language work: small ergonomic wins that compound into substantially more readable code. This post walks through what Predicate.not does, how it relates to the existing negate() instance method, how the compiler resolves it, and where it fits in real-world Stream pipelines.

What is Java 11 Predicate not?

Predicate.not is a static factory method declared on the java.util.function.Predicate interface. Its signature is static <T> Predicate<T> not(Predicate<T> target), and the body is one line: return (Predicate<T>) target.negate();. In other words, Predicate.not(target) is exactly equivalent to target.negate(), but written in the opposite syntactic order. The static form matters because Java method references like String::isEmpty and Objects::nonNull are not expressions you can post-fix with .negate() in source code without first assigning them to a variable. Predicate.not accepts the method reference directly, which keeps filter and removeIf pipelines in one fluent line.

Conceptually, Predicate belongs to the functional family of one-argument boolean-valued functions, alongside java.util.function.Function and java.util.function.Consumer. The not method belongs to the same logical-combinator subfamily as the existing default methods and, or, and negate, all of which compose two predicates into one. The difference is that not is a static entry point: it lives on the interface type rather than on an instance, mirroring other static factories like Predicate.isEqual.

How Java 11 Predicate not Works - Step by Step

Step 1: Start with a source predicate. For example, String::isEmpty is a method reference that the compiler treats as a Predicate<String> because it takes a String and returns a boolean. Likewise Predicate.isEqual("admin") is a static factory that already produces a Predicate<String>.

Step 2: Wrap it with Predicate.not. The not method takes the source predicate as its argument and returns a new predicate whose test(T t) method delegates to target.negate().test(t). At runtime, the negated predicate evaluates target.test(t) and flips the boolean result.

Step 3: Use the negated predicate where a Predicate is expected. The two most common consumers are Stream.filter(Predicate) and Collection.removeIf(Predicate). Both accept the negated predicate directly, with no extra wrapping.

Step 4: Read the pipeline left to right. The expression list.stream().filter(Predicate.not(String::isEmpty)).toList() reads naturally as "keep elements that are not empty strings", in the same word order as the English sentence. Compare with list.stream().filter(((Predicate<String>) String::isEmpty).negate()).toList(), which forces a cast to Predicate before negate() can be called on the method reference, and reads in the opposite order from English.

Step 5: Beware of double negation. Predicate.not(Predicate.not(String::isEmpty)) is legal but produces a predicate that is logically equal to String::isEmpty, just slower. Style guides recommend flattening such cases by removing both not calls.

Java Program for Predicate.not

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

public class PredicateNotDemo {

    static boolean isShort(String s) {
        return s != null && s.length() < 4;
    }

    public static void main(String[] args) {
        List<String> words = Arrays.asList(
                "", "hi", "ok", "java", "go", "", "kotlin", "ai");

        // (1) Negate a method reference cleanly
        List<String> nonEmpty = words.stream()
                .filter(Predicate.not(String::isEmpty))
                .collect(Collectors.toList());
        System.out.println("(1) non-empty: " + nonEmpty);

        // (2) Negate a custom static method reference
        List<String> notShort = words.stream()
                .filter(Predicate.not(PredicateNotDemo::isShort))
                .collect(Collectors.toList());
        System.out.println("(2) not short: " + notShort);

        // (3) Negate Predicate.isEqual for "not admin" filter
        List<String> roles = Arrays.asList("admin", "user", "guest", "admin", "user");
        List<String> nonAdmins = roles.stream()
                .filter(Predicate.not(Predicate.isEqual("admin")))
                .collect(Collectors.toList());
        System.out.println("(3) non-admins: " + nonAdmins);

        // (4) Negate Objects::isNull for null-safety filter
        List<String> withNulls = Arrays.asList("a", null, "b", null, "c");
        List<String> present = withNulls.stream()
                .filter(Predicate.not(Objects::isNull))
                .collect(Collectors.toList());
        System.out.println("(4) present: " + present);

        // (5) removeIf with Predicate.not
        List<String> mutable = new java.util.ArrayList<>(words);
        mutable.removeIf(Predicate.not(String::isEmpty));
        System.out.println("(5) after removeIf not isEmpty: " + mutable);

        // (6) Show equivalence with the older negate() style
        List<String> viaNegate = words.stream()
                .filter(((Predicate<String>) String::isEmpty).negate())
                .collect(Collectors.toList());
        System.out.println("(6) via negate():  " + viaNegate);
        System.out.println("(6) via not():    " + nonEmpty);
        System.out.println("(6) equal lists:  "
                + viaNegate.equals(nonEmpty));

        // (7) Combining with .and for compound predicates
        Predicate<String> keep = Predicate.not(String::isEmpty)
                .and(Predicate.not(PredicateNotDemo::isShort));
        List<String> longEnough = words.stream()
                .filter(keep)
                .collect(Collectors.toList());
        System.out.println("(7) non-empty AND not short: " + longEnough);
    }
}

Code Explanation - Line by Line

The isShort helper is a static method that returns true when the input String is non-null and shorter than four characters. We use it as a method reference PredicateNotDemo::isShort to demonstrate that Predicate.not works with any static method whose signature matches (T) -> boolean, not just the built-in String and Objects methods.

In section (1), the stream pipeline filters the words list, keeping only elements that do not satisfy String::isEmpty. Predicate.not wraps the method reference and produces a Predicate<String> whose test method returns !target.test(t). The collect terminal operation materializes the surviving elements into a List.

Section (2) does the same thing but with our custom isShort method, demonstrating that not is not restricted to the JDK's built-in predicates. Section (3) nests Predicate.not around Predicate.isEqual("admin") to express "not equal to admin" cleanly; the alternative Predicate.isEqual("admin").negate() reads as "equal to admin, negated", which is more verbose.

Section (4) uses Predicate.not(Objects::isNull) as the modern replacement for the older Objects::nonNull idiom. The two are functionally equivalent, but using not with isNull lets you write filter pipelines that mirror the natural English "filter out nulls" phrasing.

Section (5) demonstrates the most popular real-world use of Predicate.not: list.removeIf(Predicate.not(String::isEmpty)) mutates the list in place, removing every element that is not an empty string. Because removeIf takes a Predicate, not drops in seamlessly.

Section (6) is a behavioural equivalence check. The viaNegate pipeline casts String::isEmpty to Predicate<String> explicitly so that .negate() can be called on the method reference inline. The viaNot pipeline uses Predicate.not(String::isEmpty). The two output lists are equal, confirming that not is syntactic sugar over negate for the same target.

Section (7) chains Predicate.not with .and to build a compound predicate that keeps only elements that are both non-empty and not short. The fluent combinator style of and, or, and not composes cleanly into multi-clause filters without resorting to lambdas.

Sample Input and Output

Input:  ["", "hi", "ok", "java", "go", "", "kotlin", "ai"]
Output:
(1) non-empty: [hi, ok, java, go, kotlin, ai]
(2) not short: [java, kotlin]
(3) non-admins: [user, guest, user]
(4) present: [a, b, c]
(5) after removeIf not isEmpty: [, ]
(6) via negate():  [hi, ok, java, go, kotlin, ai]
(6) via not():    [hi, ok, java, go, kotlin, ai]
(6) equal lists:  true
(7) non-empty AND not short: [java, kotlin]

The output confirms that Predicate.not(String::isEmpty) filters out empty strings, Predicate.not(isShort) filters out short strings, and that the not and negate() forms produce identical lists. Note that section (5) prints the two empty strings that survived the removeIf: the list started with eight elements, and only the two empty strings survived removal.

Common Mistakes to Avoid

The first mistake is calling Predicate.not on an instance rather than statically. Beginners sometimes write list.removeIf(s -> s.not(...)), which fails to compile because not is a static method on the Predicate interface, not an instance method on a String. The correct call is Predicate.not(String::isEmpty).

The second mistake is double-negating by accident. Predicate.not(Predicate.not(String::isEmpty)) compiles and runs, but it is logically equivalent to String::isEmpty and obscures the intent of the code. Style guides recommend folding double negations into the simpler positive form before submitting code for review.

The third mistake is assuming Predicate.not works on any lambda without an explicit target type. The expression Predicate.not(s -> s.isEmpty()) compiles because the compiler can infer the type of the lambda parameter from the formal parameter type of not, but Predicate.not(s -> s.length() > 3) without context may fail to compile if the surrounding context does not pin down T. Assigning the lambda to a Predicate<String> variable first avoids this problem.

The fourth mistake is mixing up not with the older negate() instance method when posting code to old Java 8 codebases. Predicate.not only exists from Java 11 onward, so code that needs to compile on Java 8 must use the explicit-cast form ((Predicate<String>) String::isEmpty).negate() instead.

Real-World Applications

In production Java code, Predicate.not shows up most often in Stream.filter and Collection.removeIf pipelines that filter out nulls, blanks, or sentinel values. Spring Framework's internal utilities use Predicate.not(Objects::isNull) and Predicate.not(String::isBlank) extensively when collecting headers, query parameters, and bean names. The Hibernate Validator codebase uses Predicate.not to filter out constraints that should not apply to a given property, often combined with Predicate.and to express multi-clause conditions.

In testing libraries, JUnit 5 assertions and assumptions use Predicate.not to assert that a value does not satisfy a condition, for example asserting that a list does not contain a particular element via assertAll with a stream of negative predicates. In Apache Camel route definitions, Predicate.not is used to invert route conditions, such as "when the body is not empty, route to the file endpoint".

Even when not directly invoked, the existence of Predicate.not on the JDK influences coding style across the ecosystem: libraries that previously shipped their own NegatePredicate utility classes, like Guava's Predicates.not, are now often used only for backwards compatibility, with new code preferring the JDK's Predicate.not for the standard library's promise of long-term support.

Conclusion

Java 11 Predicate.not is a small, focused addition to the JDK that gives the functional Predicate interface a static negation factory, mirroring Predicate.isEqual and other static factories. By accepting a method reference directly, java 11 predicate not lets filter and removeIf pipelines stay fluent and read in the same direction as English. Next, study Predicate.and and Predicate.or to compose multi-clause conditions, and then read up on Java 16's Pattern Matching for instanceof, which similarly cleans up repetitive type-check-and-cast code with a single language-level construct.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments