1. Introduction
Predicate is one of the predefined Java functional interfaces. A functional interface is an interface that contains only one abstract method. Java has plenty of predefined functional interfaces, they are located in java.util.function package. More documentation on Java functional interfaces could be found on this link. This article will show how to create simple Predicate and use it to filter list of Integer numbers.
2. Example
In this example, we'll show how to create a simple predicate that checks if the number is odd. Then, we'll use this predicate to filter a list of integer numbers using stream.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateExample{
public static void main(String[] args) {
Predicate<Integer> isOddNumber = value -> value % 2 == 1;
List<Integer> numbersToFilter = Arrays.asList(2, 5, 4, 1, 34, 57);
List<Integer> filteredList = filterOddNumbers(numbersToFilter, isOddNumber);
System.out.println(filteredList);
}
public static List<Integer> filterOddNumbers(List<Integer> numbersToFilter, Predicate<Integer> predicate) {
return numbersToFilter.stream().filter(predicate).collect(Collectors.toList());
}
}
In sample code, the predicate is defined as a lambda function that, after invoked, resolves as a boolean. We can see that this predicate is invoked in the method filterOddNumbers that accepts a list of Integer numbers and predicate as input variables. Then we turn this list into a stream and invoke filter function on it. Filter function accepts Predicate as an input variable.
3. Conclusion
In this article we presented Java Predicate and explained how to use Predicate to filter stream in Java. More documentation on Predicate could be found in the Oracle official documentation.