Thursday, June 25, 2026

Java: Negating a Predicate

 This article was originally publixhed on JRoller on September 12, 2016

Often, when using Java streams, I try to replace my lambdas with Method References. For instance, when I have this code:

    mystream.filter(mystring -> mystring.isEmpty()) ...

I tend to replace it with that one:

    mystream.filter(String::isEmpty) ...

Except that this code is not really useful. I rarely filter my stream with empty Strings. Usually, I do quite the opposite:

    mystream.filter(mystring -> !mystring.isEmpty()) ...

Now with that one small symbol, I managed to make my day more difficult. What to do if I really want to use Method References? I can create a isNotEmpty() method, but I don't want to do that for all my methods that return a boolean. If I really insist, I can end up with this ugly code:

    mystream.filter(((Predicate<String>)String::isEmpty).negate()) ...

One way to make things nice again, is to create a helper method, like this one:

    public static <T> Predicate<T> not(Predicate<T> p) {
        return p.negate();
    }

Now, I can simply use it like this:

    mystream.filter(not(String::isEmpty)) ...

I heard that such a method might find its way into JDK 9. Someone heard anything more concrete?

It turned out that Predicate.not() was introduced in Java 11.

No comments:

Post a Comment