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

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    default Predicate negate() {
        return (t) -> !test(t);
    }

    default Predicate or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    static  Predicate isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

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.

public class PredicateExample implements Predicate<String> {
    public boolean test(String s) {
        return s.isEmpty();
    }
}

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.

Predicate<String> predicate = t -> t.isEmpty();

Leave a Reply

What is the Java Predicate Interface?