In this example we take a look at the Predicate Functional Interface to filter a List of Employee objects based on a condition where salary is > 40k.
package org.code2care.examples;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
class Employee {
private String empName;
private int empAge;
private double empSalary;
public Employee(String name, int age, double salary) {
this.empName = name;
this.empAge = age;
this.empSalary = salary;
}
public String getEmpName() {
return empName;
}
public int getEmpAge() {
return empAge;
}
public double getEmpSalary() {
return empSalary;
}
}
public class EmployeePredicateExample {
public static void main(String... args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Andy", 21, 40000.0));
employees.add(new Employee("Sharma", 25, 71000.0));
employees.add(new Employee("Luke", 22, 42000.0));
employees.add(new Employee("Mikey", 24, 56000.0));
// Predicate to filter employees with a salary above 40k
Predicate<Employee> highSalaryFilter = employee -> employee.getEmpSalary() > 40000.0;
List<Employee> highSalaryEmployees = filterEmployees(employees, highSalaryFilter);
System.out.println("Employees with High Salary:");
for (Employee employee : highSalaryEmployees) {
System.out.println("Name: " + employee.getEmpName() + ", Age: " + employee.getEmpAge() + ", Salary: $" + employee.getEmpSalary());
}
}
private static List<Employee> filterEmployees(List<Employee> employees, Predicate<Employee> predicate) {
List<Employee> filteredList = new ArrayList<>();
for (Employee employee : employees) {
if (predicate.test(employee)) {
filteredList.add(employee);
}
}
return filteredList;
}
}
Output:
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!