How can I negate a lambda Predicate?

13,235

Solution 1

You would have to do .filter(((Predicate<String>) String::isEmpty).negate())

If you want, you can define

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

and then

.filter(not(String::isEmpty))

but I would just stick with v -> !v.isEmpty()

Solution 2

It seems like you have to cast to Predicate<String> for this to work:

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

Of course, it would be much shorter to use a lambda in this case:

.filter(s -> ! s.isEmpty())

Solution 3

Instead of creating classes by yourself use durian utility library. It has a lot of methods: and, or and not of course:

import static com.diffplug.common.base.Predicates.not;

stream
.filter(Objects::nonNull)
.map(String::trim)
.filter(not(String::isEmpty));
Share:
13,235
Jin Kwon
Author by

Jin Kwon

I'm a Java learner.

Updated on June 12, 2022

Comments

  • Jin Kwon
    Jin Kwon almost 2 years

    Lets say I have a Stream of Strings.

    final Stream<String> stream = ...;
    

    I want to filter out each empty string after trimmed.

    stream
        .filter(Objects::nonNull)
        .map(String::trim)
        .filter(v -> !v.isEmpty());
    

    Is there any way to apply Predicate#negate() for replacing v -> !v.isEmpty() part?

    .filter(((Predicate) String::isEmpty).negate()) // not compile