Java: How to Filter a List using Predicate


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:

Employees with High Salary:
Name: Sharma, Age: 25, Salary: $71000.0
Name: Luke, Age: 22, Salary: $42000.0
Name: Mikey, Age: 24, Salary: $56000.0


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap