Welcome to Java4u

A Single Place for all Java Resources

Looking for something?

Subscribe to this blog!

Receive the latest posts by email.

.Just enter your email below if you want to subscribe!

Email

Friday, June 13, 2014

Java 8 : Predicate



In mathematics, a predicate is commonly understood to be a Boolean-valued function P: X? {true, false}, called the predicate on X. Informally, a predicate is a statement that may be true or false depending on the values of its variables. It can be thought of as an operator or function that returns a value that is either true or false. 

In java 8, Predicate a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. So, where you think, you can use these true/false returning functions in day to day programming?
 I will say you can use them anywhere where you need to evaluate a condition on group/collection of similar objects such that evaluation can result either in true or false 
 e.g.
1) Find all children borned after a particular date
2) Pizzas ordered a specific time
3) Employees greater than certain age and so on.

So Predicate seems to be interesting thing. Let’s go deeper. 
 Streamfilter(Predicate predicate);
As I said, Predicate is functional interface. It means we can pass lambda expressions wherever predicate is expected. For example one such method is filter () method from Stream interface.
               
//Returns a stream consisting of the elements of this stream that match the given predicate.
To collect and perform some operation of all elements present in Stream in one call. So, essentially we can use stream and predicate to first filter certain elements from a group and then perform some operation on it.

I.How to use Predicate on a collection 
  
 
 

II.  Final Thoughts on Predicates in java 8

1) They move your conditions (sometimes business logic) to a central place. This helps in unit-testing them separately.
2) Any change need not be duplicated into multiple places. It improves manageability of code.
3) The code e.g. “filterEmployees (employees, isAdultFemale ())” is very much readable than writing a if-else block.
Well those are my thoughts. What do you think of this feature? Share with all of us in comments section.

 

 
 

0 comments: