All about Predicates in Java, Google(Guava), Apache with examples

This article covers all aspects of predicates in Java (java.util.function.Predicate, java.util.function.BiPredicate), Google API Guava (com.google.common.base.Predicate) & Apache API commons-collection (org.apache.commons.collections4.Predicate) through several examples.

java.util.function.Predicate

java.util.function.Predicate is a functional interface which provides ability to test certain criteria based on single argument. Here are code examples of java.util.function.Predicate in simple use, lambda, streams. Example also shows how multiple predicates can be combined using AND & OR operations & how existing predicate can be negated.



java.util.function.BiPredicate

java.util.function.BiPredicate is a functional interface which provides ability to test any criteria based on two arguments. Multiple bipredicates can be combined using NAD or OR operations.



Multi argument predicate like Tri Predicate or Tetra Predicate or so ..

If more than 2 arguments are required for predicate, then its better to wrap those arguments in single object & pass to single argument predicate.



com.google.common.base.Predicate

com.google.common.base.Predicate is sub-interface of Java’s java.util.function.Predicate since 2.0 version of Guava. So google predicate can be used same as java.util.function.Predicate.

But here is the real advantage that guava can still offer if use guava predicate. Guava offers utility class com.google.common.base.Predicates which provides lot of good-to-use utility methods for predicates. Here are examples.



org.apache.commons.collections4.Predicate

org.apache.commons.collections4.Predicate does not extend java’s  java.util.function.Predicate so might not work directly in lambda. But Apache’s predicate does provides many in-built predicates.



 

Leave a Reply

Your email address will not be published.