How to express a predicate of equality in Java?

Asked

Viewed 77 times

3

I have the following expression:

final String idStatusAutorizada = ...; // valor constante
return pendencias.stream()
    .map(TipoBlocCarga::getIdStatus)
    .anyMatch(idStatusPendencia -> !idStatusAutorizada.equals(idStatusPendencia));

But the latter lambda is not satisfying me aesthetically. I would like to turn into some kind of method reference. Another alternative that I don’t like is to declare a variable with the predicate of idStatusAutorizada::equals and pass the method to the function of that predicate with negate(), but I must say that I do not yet seem sufficiently elegant:

final String idStatusAutorizada = ...; // valor constante
Predicate<String> equalsAutorizada = idStatusAutorizada::equals;
return pendencias.stream()
    .map(TipoBlocCarga::getIdStatus)
    .anyMatch(equalsAutorizada.negate());

I would find it beautiful if it were possible to do idStatusAutorizada::equals.negate(), but Java 8 does not allow this. I don’t know if this has changed in the latest versions, but I can’t change the version of Java in my code because of the platforms on which the code will be executed.

So, my question: is it possible to make a predicate of equality in Java?

1 answer

5


The solutions below are a compilation of the answers of this question.


If you want to use the method Reference and does not want to create a variable just to save the Predicate, can even do. It’s just not as "beautiful" as you’d like, because it involves making a cast of method Reference for Predicate, so it is possible to call the method negate:

return pendencias.stream()
    .map(TipoBlocCarga::getIdStatus)
    .anyMatch(((Predicate<String>) idStatusAutorizada::equals).negate());

Maybe I got even more "ugly" than your alternatives...


Starting from Java 11, there is the static method Predicate.not, to which you can directly pass the method Reference:

return pendencias.stream()
    .map(TipoBlocCarga::getIdStatus)
    .anyMatch(Predicate.not(idStatusAutorizada::equals));

But if you are using Java < 11, there is still the possibility to create a similar method:

public static <T> Predicate<T> not(Predicate<T> predicate) {
    return predicate.negate();
}

...
return pendencias.stream()
    .map(TipoBlocCarga::getIdStatus)
    .anyMatch(not(idStatusAutorizada::equals));
  • 2

    It cannot be said that Java has not been striving to evolve xD. This last one even without Java 11 was great at readability level.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.