Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 877
Jin Kwon Avatar asked Jan 30 '15 12:01

Jin Kwon


People also ask

How do you negate a predicate?

To negate a sequence of nested quantifiers, you flip each quantifier in the sequence and then negate the predicate. So the negation of ∀x ∃y : P(x, y) is ∃x ∀y : P(x, y) and So the negation of ∃x ∀y : P(x, y) and ∀x ∃y : P(x, y).

What is neg predicate in Java 8?

Predicate negate() Method The Predicate. negate() method returns the logical negation of an existing predicate. Predicate<Integer> isEven = i -> i % 2 == 0; Predicate<Integer> isOdd = isEven.


1 Answers

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

like image 100
Misha Avatar answered Sep 23 '22 01:09

Misha