When we want to test some criteria on collection object’s element and depending upon result test result (true or false) we perform some operation on that collection or its elements, we should use predicate.
Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.
Predicate<T> is a functional construct providing a convenient way of basically testing if something is true of a given T object.
For example suppose we have to find all even number from list, we do like:
Or with help of lambdas expression we can do like:
Suppose we have a class
Now let’s say I have a List employees and I want to know if there’s anyone named “Ajay” in the list.
Without using a Predicate, I always perform this as below:
This is fine, but then we want to check if there’s a employee named “Saurav”? Or a employee whose id is 101?
Using a Predicate, we can find these things using a LOT less code:
Using even write short code for predicate using lambdas expression:
I hope that you have now better understanding of Predicate.
Please leave a comment, it encourage me to write quality articles.
Happy reading and Coding 🙂