javapredicatejava-8negate

How to negate a method reference predicate


In Java 8, you can use a method reference to filter a stream, for example:

Stream<String> s = ...;
long emptyStrings = s.filter(String::isEmpty).count();

Is there a way to create a method reference that is the negation of an existing one, i.e. something like:

long nonEmptyStrings = s.filter(not(String::isEmpty)).count();

I could create the not method like below but I was wondering if the JDK offered something similar.

static <T> Predicate<T> not(Predicate<T> p) { return o -> !p.test(o); }

Solution

  • Predicate.not( … )

    offers a new method Predicate#not

    So you can negate the method reference:

    Stream<String> s = ...;
    long nonEmptyStrings = s.filter(Predicate.not(String::isEmpty)).count();