Java 8 - Filtering data with java.util.function.Predicate
Java 8 introduced new features like Streaming API, Lambdas, functional interface, default methods in interface and many more. Today, we will discuss Predicate interface from java.util.function package and its usage in filtering data.
What is java.util.function.Predicate?
java.util.function.Predicate can be considered a conditional checker which accepts one argument of type T and return the boolean value.
It is a functional interface with functional method test(Object). Here Object is typed.
@FunctionalInterface
interface Predicate<T> {
public boolean test(T t);
}
How we can filter records with Predicates?
Lets jump to example code. Suppose we have Collection of Employee and we want to filter them based on age, sex, salary etc.
Let's first define Employee pojo.
class Employee {
private long id;
private String firstName;
private String lastName;
private int age;
private Sex sex;
private int salary;
// getters, constructor, hashCode, equals, to String
}
Defining different predicates for filtering
Predicate<Employee> male = e -> e.getSex() == Sex.MALE;
Predicate<Employee> female = e -> e.getSex() == Sex.FEMALE;
Predicate<Employee> ageLessThan30 = e -> e.getAge() < 30;
Predicate<Employee> salaryLessThan20 = e -> e.getSalary() < 20000;
Predicate<Employee> salaryGreaterThan25 = e -> e.getSalary() > 25000;
Filtering employees with Predicates
employees.stream().filter(male).collect(Collectors.toList()); employees.stream().filter(female).collect(Collectors.toList()); employees.stream().filter(ageLessThan30).collect(Collectors.toList()); employees.stream().filter(salaryLessThan20).collect(Collectors.toList());
Here, employees field is of type java.util.List. Collection framework is retrofitted for Streaming API and filter function is defined in Streams. We streamed collection of employees. we filtered them based on the Predicate and then collect them to List.
You can read about Predicate Chaining here.
Thanks,
Gaurav