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: Employeepackage 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:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!