Question: Negating Java 8 reference to Predicate method


Negating Java 8 reference to Predicate method

Answers 0
Added at 2017-01-02 17:01

In Java 8, it is possible to refer to unary methods which return a boolean/Boolean (e.g. Collection.contains(Object)) using method reference syntax, returning an equivalent Predicate object for the referent method:

final Set<Integer> acceptedValues = new HashSet<>();
final Predicate<Integer> isValueAccepted = acceptedValues::contains;

Moreover, the negation of this object can be retrieved by using Predicate.negate():

final Predicate<Integer> isValueNotAccepted = isValueAccepted.negate();

However, is there no shorthand for directly negating a method reference itself? — for example, the following expressions are not compilable:

  • final Predicate<Integer> isValueNotAccepted = acceptedValues::contains::negate;
  • final Predicate<Integer> isValueNotAccepted = acceptedValues::contains.negate();
  • final Predicate<Integer> isValueNotAccepted = !acceptedValues::contains;

Answers to

Negating Java 8 reference to Predicate method

Source Show
◀ Wstecz