I have seen in some projects that people use Predicate
s 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 Predicate
s over if statements?
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 Predicate
s 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.