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?
The predicate is a predefined functional interface in Java defined in the java. util. Function package. It helps with manageability of code, aids in unit-testing, and provides various handy functions.
You use a Predicate (javadoc) when you need a function that takes one argument and returns a boolean . For example, you can use a Predicate in a situation where you want to filter a stream to remove elements that don't satisfy some logical condition, or find the first element that satisfies the condition.
Java IntPredicate interface is a predicate of one int-valued argument. It can be considered an operator or function that returns a value either true or false based on certain evaluation on the argument int value. IntPredicate is a functional interface whose functional method is boolean test(int a) .
Function interface is used to do the transformation.It can accepts one argument and produces a result. On the other side, Predicate can also accept only one argument but it can only return boolean value. It is used to test the condition.
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.
For the exact example that you provided, using a Predicate is a big over-kill. The compiler and then the runtime will create:
- a method (de-sugared predicate)
- a .class that will implement java.util.Predicate
- 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With