Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
Predicates vs if statements

I have seen in some projects that people use Predicates instead of pure if statements, as illustrated with a simple example below:

    int i = 5;
    // Option 1
    if (i == 5) {
        // Do something
        System.out.println("if statement");
    }

    // Option 2
    Predicate<Integer> predicate = integer -> integer == 5;
    if (predicate.test(i)) {
        // Do something
        System.out.println("predicate");
    }

What's the point of preferring Predicates over if statements?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Using a predicate makes your code more flexible.

Instead of writing a condition that always checks if i == 5, you can write a condition that evaluates a Predicate, which allows you to pass different Predicates implementing different conditions.

For example, the Predicate can be passed as an argument to a method :

public void someMethod (Predicate<Integer> predicate) {
    if(predicate.test(i)) {
        // do something
        System.out.println("predicate");
    }
    ...
}

This is how the filter method of Stream works.

about 4 years ago · Santiago Trujillo Relatório

0

For the exact example that you provided, using a Predicate is a big over-kill. The compiler and then the runtime will create:

  1. a method (de-sugared predicate)
  2. a .class that will implement java.util.Predicate
  3. an instance of the class created at 2

all this versus a simple if statement.

And all this for a stateless Predicate. If your predicate is statefull, like:

 Predicate<Integer> p = (Integer j) -> this.isJGood(j); // you are capturing "this"

then every time you will use this Predicate, a new instance will be created (at least under the current JVM).

The only viable option IMO to create such a Predicate is, of course, to re-use it in multiple places (like passing as arguments to methods).

about 4 years ago · Santiago Trujillo Relatório

0

Using if statements is the best (read: most performant) way to check binary conditions.

The switch statement may be faster for more complex situations.

A Predicate are a special form of Function. In fact the java language architect work on a way to allow generic primitive types. This will make Predicate<T> roughly equivalent to Function<T, boolean> (modulo the test vs apply method name).

If a function (resp. method) takes one or more functions as argument(s), we call it higher-order function. We say that we are passing behaviour to a function. This allows us to create powerful APIs.

String result = Match(arg).of(
        Case(isIn("-h", "--help"),    help()),
        Case(isIn("-v", "--version"), version()),
        Case($(),                     cmd -> "unknown command: " + cmd)
);

This example is taken from Javaslang, a library for object-functional programming in Java 8+.

Disclaimer: I'm the creator of Javaslang.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda