What is the Java Predicate Interface?

The Java Predicate interface of the java.util.function package is a functional interface that is often used as an assignment target for lambda expressions.  The test(T t) method is the class’s only abstract method, leaving it as the only one without a default implementation.  Here is an overview of the various methods in the Predicate interface:

  • test(T t) is the interface’s single abstract method which takes an object as input and returns a boolean.
  • and(Predicate<? super T> other) provides a simple way to string together Predicates creating logical (short circuiting) ANDs.
  • or(Predicate<? super T> other) provides a simple way to string together Predicates creating logical (short circuiting) ORs.
  • negate()returns a Predicate that will evaluate the opposite as the calling Predicate.

For more information on functional interfaces in Java click here: What is a Java Functional Interface?.
For more information on lambdas in Java click here: What are Lambdas in Java?

 

Predicate Interface Source Code

Predicate Interface Example

Below is an example of creating the PredicateExample class by implementing Predicate. The test(T t) method takes a string and evaluates if it is empty.

Creating a Predicate Instance with Lambda Expression

Below is an example of using a lambda expression to create an instance of Predicate. The test(T t) method takes a string and evaluates if the string is empty.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">