I am going through the code which uses Predicate in Java. I have never used Predicate. Can someone guide me to any tutorial or conceptual explanation of Predicate and its implementation in Java?
I am going through the code which uses Predicate in Java. I have never
Share
I’m assuming you’re talking about
com.google.common.base.Predicate<T>from Guava.From the API:
This is essentially an OOP abstraction for a
booleantest.For example, you may have a helper method like this:
Now, given a
List<Integer>, you can process only the even numbers like this:With
Predicate, theiftest is abstracted out as a type. This allows it to interoperate with the rest of the API, such asIterables, which have many utility methods that takesPredicate.Thus, you can now write something like this:
Note that now the for-each loop is much simpler without the
iftest. We’ve reached a higher level of abtraction by definingIterable<Integer> evenNumbers, byfilter-ing using aPredicate.API links
Iterables.filterOn higher-order function
PredicateallowsIterables.filterto serve as what is called a higher-order function. On its own, this offers many advantages. Take theList<Integer> numbersexample above. Suppose we want to test if all numbers are positive. We can write something like this:With a
Predicate, and interoperating with the rest of the libraries, we can instead write this:Hopefully you can now see the value in higher abstractions for routines like “filter all elements by the given predicate”, “check if all elements satisfy the given predicate”, etc make for better code.
Unfortunately Java doesn’t have first-class methods: you can’t pass methods around to
Iterables.filterandIterables.all. You can, of course, pass around objects in Java. Thus, thePredicatetype is defined, and you pass objects implementing this interface instead.See also