Predicates vs if statements

poyger picture poyger · Mar 16, 2017 · Viewed 11.4k times · Source

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?

Answer

Eran picture Eran · Mar 16, 2017

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.