Predicate Interface

Lambda

Predicate Interface


The Predicate is a built-in functional interface included in Java SE 8 in the java.util.function package, which can be used in cases when an object should be evaluated for a given test condition and a boolean result of test should be returned.

Example 1. java.util.function.Predicate Interface

The definition of the interface is shown in the example:

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
    ...
}

Function descriptor of the interface is:

T -> boolean

Example 2. Usage of java.util.function.Predicate Interface

This example describes the simple use of Predicate interface, where it is verified whether the input integer is negative or not:

Predicate<Integer> negative = i -> i < 0;
System.out.println(negative.test(-6));
System.out.println(negative.test(6));
System.out.println(negative.test(0));

The interface also has default methods, which return a composed Predicate that represents a short-circuiting logical AND and OR of this predicate and a logical negation:

default Predicate<T> and(Predicate<? super T> other) 
default Predicate<T> negate()
default Predicate<T> or(Predicate<? super T> other) 

Example 3. Usage of default methods of java.util.function.Predicate Interface

Example demonstrates how to use default methods of Predicate interface:

Predicate<String> containsA = t -> t.contains("A");
Predicate<String> containsB = t -> t.contains("B");
System.out.println(containsA.and(containsB).test("ABCD"));

Predicate interface has also a static method, that tests if two arguments are equal according to Objects.equals(Object, Object):

static <T> Predicate<T> isEqual(Object targetRef)

 

Sources: Chapter TEN - Java Built-In Lambda Interfaces, Java 8 Programmer II Study Guide by Esteban Herrera.



0 comments
Leave your comment: