Java: Pass Predicate as Parameter to a Method Example


By passing a Predicate as a parameter to a method in Java makes the code more flexible and reusable.

Let's take a look at an example.

Class: Employee
package org.code2care.examples;

public class Employee {

    private String empName;
    private int empAge;

    public Employee(String empName, int empAge) {
        this.empName = empName;
        this.empAge = empAge;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getEmpAge() {
        return empAge;
    }

    public void setEmpAge(int empAge) {
        this.empAge = empAge;
    }
}
PredicateAsParameterExample
package org.code2care.examples;

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;


public class PredicateAsParameterExample {

    public static void main(String... args) {

        List<Employee> employees = List.of(

                new Employee("Mike", 22),
                new Employee("Sam", 32),
                new Employee("Alan", 24),
                new Employee("Alex", 32)
        );

        List<Employee> youngEmployees = filterEmployees(employees, employee -> employee.getEmpAge() < 30);

        youngEmployees.forEach(employee -> System.out.println(employee.getEmpName() + " is a young employee."));
    }

    public static List<Employee> filterEmployees(List<Employee> employees, Predicate<Employee> condition) {

        return employees.stream().filter(condition).collect(Collectors.toList());
    }
}
Output:

Mike is a young employee.
Alan is a young employee.

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