Functional Interface Predicate

Java Predicate: A Comprehensive Guide with Examples photo

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 the test should be returned.

Example 1. java.util.function.Predicate Interface

The definition of the interface is shown in the example:

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 the Predicate interface, where it is verified whether the input integer is negative or not:

Predicate<Integer> negative = i -> i < 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

The example demonstrates how to use default methods of Predicate interface:

Predicate<String> containsA = t -> t.contains("A");
Predicate<String> containsB = t -> t.contains("B");

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)
Читайте также: