Say I have a List of objects of the following type:
public class Employee {
private String emplId;
private Name name;
private String dept;
private String city;
}
And I have the following list:
List<Employee> empLst = Arrays.asList(
new Employee("1", "henry", "10", "Boston"),
new Employee("2", "Foster", "10", "san jose"),
new Employee("3", "Rick", "10", "sfo"),
new Employee("4", "Ban", "20", "Boston"),
new Employee("5", "Zen", "20", "Ale"),
new Employee("6", "Ken", "30", "sfo")
);
How can I implement a search which accepts an employee object and filters the list that matches query object values?
GetEmplList(new Employee().setCity("Boston")); // returns both #1 and #4 employees
GetEmplList(new Employee().setCity("Boston").setDept("20")); // returns only #4 employee
GetEmplList(new Employee().setName("Ken")); // returns only #6 employees
I don't want something like the following compile-time filter:
empLst.stream()
.filter(e -> e.getCity().equalsIgnoreCase("Boston"))
.forEach(e -> System.out.println(e.getName()));
You need a
Predicatematching an element with a provided 'example'. Properties beingnullin the example should be considered matching.Usage:
Or a more generic implementation of
Predicateusing reflection, which can work for any class: