Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 315
assylias Avatar asked Jan 31 '14 19:01

assylias


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.

Is not method in Java?

The not operator is a logical operator, represented in Java by the ! symbol. It's a unary operator that takes a boolean value as its operand. The not operator works by inverting (or negating) the value of its operand.


1 Answers

Predicate.not( … )

java-11 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(); 
like image 144
Anton Balaniuc Avatar answered Sep 25 '22 23:09

Anton Balaniuc