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); }

12 Answers
12

Leave a Comment