The Predicate<T> Interface and Its test Method
What you'll learn: You'll understand how Predicate<T> represents a boolean-valued function with a single test method that evaluates conditions.
What Is Predicate<T>?
Predicate<T> is a functional interface from java.util.function that represents a function taking one argument and returning a boolean value. Think of it as a "question asker" — you give it something, and it answers true or false.
The interface has one abstract method:
boolean test(T t)
This method takes an input of type T and returns true or false based on some condition.
Structure and Purpose
Since Predicate<T> is a functional interface, it fits the Single Abstract Method (SAM) rule perfectly. The test method is its only abstract method, making Predicate compatible with lambda expressions.
Common use cases:
- Filtering elements in collections
- Validating input
- Conditional logic in streams
Simple Example
import java.util.function.Predicate;
Predicate<Integer> isPositive = number -> number > 0;
System.out.println(isPositive.test(5)); // true
System.out.println(isPositive.test(-3)); // false
System.out.println(isPositive.test(0)); // false
Here, isPositive is a Predicate<Integer> that tests whether a number is positive. The lambda number -> number > 0 implements the test method.
Analogies
Think of Predicate like a bouncer at a club: you present someone (the input), and the bouncer decides whether they pass the test (get in) or fail it (stay out).
Key Takeaway: Predicate<T> is a functional interface with a single abstract method test(T t) that takes one argument and returns a boolean, making it ideal for representing conditions and filters.