Jin Kwon Jin Kwon - 3 years ago 104
Java Question

How can I negate a lambda Predicate?

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

Answer Source

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()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download