What Is a Predicate Interface In Java?
Table of Contents
It takes an object and checks to see if that object satisfies some criteria. We use this in matching/filtering data.
The Predicate takes one argument, and returns a Boolean.
The Predicate
interface is a functional interface defined in the java.util.function
package. It represents a function that takes an input of one type and returns a boolean value, indicating whether the input satisfies a certain condition.
The Predicate
interface is commonly used for filtering, testing, or validating elements in collections or streams.
The Predicate
interface declares a single abstract method called test()
, which takes an argument of the input type and returns a boolean value.
Here's the method signature of the test()
method:
boolean test(T t);
The type parameter T
represents the type of input to be tested. It can be any valid Java type, including primitive types and objects.
To use the Predicate
interface, you can create an instance of it using a lambda expression or method reference that implements the test()
method. Here's an example that demonstrates how to use a Predicate
to filter even numbers from a list of integers:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Predicate<Integer> evenNumberPredicate = num -> num % 2 == 0;
// Filtering even numbers from the list
List<Integer> evenNumbers = filter(numbers, evenNumberPredicate);
System.out.println("Even numbers: " + evenNumbers);
}
public static List<Integer> filter(List<Integer> list, Predicate<Integer> predicate) {
List<Integer> filteredList = new ArrayList<>();
for (Integer num : list) {
if (predicate.test(num)) {
filteredList.add(num);
}
}
return filteredList;
}
}
In the example, we create a Predicate<Integer>
using a lambda expression that tests whether a given integer is even. We then use the filter()
method, which takes a list of integers and a Predicate
as arguments, and returns a new list containing only the elements that satisfy the predicate.
The Predicate
interface is widely used in functional programming, especially in combination with collections, streams, and filtering operations. It allows for expressive and flexible filtering of elements based on various conditions.
Note that the Predicate
interface is part of the Java 8 functional interfaces introduced to support lambda expressions and functional programming constructs. It is often used alongside other functional interfaces like Consumer
, Function
, and Supplier
to build complex functional pipelines and perform advanced data processing tasks.
👨🏻💻 Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.