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); }
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).
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With