如何实现动态运行时查询来过滤java对象流

问题描述 投票:0回答:1

假设我有以下对象列表

public class Employee {

    private String emplId;
    private Name name;
    private String dept;
    private String city;
}

并且有

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")
    );

如何实现接受员工对象并过滤与查询对象值匹配的列表的搜索

GetEmplList(new Employee().setCity("Boston")) which returns both #1 and #4 employees where as 
GetEmplList(new Employee().setCity("Boston").setDept("20"))  returns only #4 employee
GetEmplList(new Employee().setName("Ken"))  returns only #6 employees
empLst.stream()
     .filter(e -> e.getCity().equalsIgnoreCase("Boston"))
     .forEach(e -> System.out.println(e.getName()));

不想要像上面编译时过滤器那样的东西`

java filter stream
1个回答
0
投票

您需要一个

Predicate
将元素与提供的“示例”相匹配。示例中为
null
的属性应视为匹配。

public class MatchByExample implements Predicate<Employee> {

  private final Employee example;

  public MatchByExample(Employee example) {
    this.example = example;
  }

  @Override
  public boolean test(Employee employee) {
    return match(example.getEmplId(), employee.getEmplId())
            && match(example.getCity(), employee.getCity())
            && match(example.getName(), employee.getName())
            && match(example.getDept(), employee.getDept());
  }

  private static boolean match(Object exampleProperty, Object propertyToTest) {
    if (exampleProperty == null) {
      //property not provided in example
      return true;
    }
    return exampleProperty.equals(propertyToTest);
  }
}

用途:

Employee example = new Employee(null, null, "20", "Boston");
List<Employee> filteredResult = empLst.stream()
        .filter(new MatchByExample(example))
        .toList();
System.out.println(filteredResult);
//prints the employee with id 4
© www.soinside.com 2019 - 2024. All rights reserved.