Lambda Expressions · Lesson 8/9
89%
⏱ 10–15 min

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:

@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 the 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

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");
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)

Java Core

1. Java Introduction
2. Run Your First Java App
3. Java Syntax
4. Java Operations
5. Operators
6. Arrays
7. Sorting Algorithms
8. OOP Basics
9. Lambda Expressions
10. Stream API
11. Inner Classes and Exceptions
12. Git & GitHub
‹ Previous lesson Next lesson ›