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.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!