仅当Java8不为空时,才使用Java8过滤多个属性

时间:2016-04-27 12:51:36

标签: java-8

我有一个像这样的对象

public class Organization {

  private List<Employee> employees;

  public static class Employee {
    private String department;
    private String designation;
  }
}

我有一个接收Map<String, Object>的搜索方法。此地图可以包含部门或指定的键值,也可以包含两者。

{department -> "cs"} or
{designation -> "engineer"} or
{department -> "cs", designation -> "engineer"} 

这就是我需要做的事情。如果部门密钥存在,我需要返回该部门的所有员工。如果存在部门和指定密钥,我需要返回符合这两个标准的所有员工。我该怎么做?

如果地图是动态的,我如何过滤员工?

2 个答案:

答案 0 :(得分:1)

最好的方法可能是运行多个过滤器:

Stream<Employee> employeeStream = employees.stream();
if (filter.get("department") != null)
    employeeStream = employeeStream.filter(e -> filter.get("department").equals(e.getDepartment()));
if (filter.get("designation") != null)
    employeeStream = employeeStream.filter(e -> filter.get("designation").equals(e.getDesignation()));
List<Employee> result = employeeStream.collect(Collectors.toList());

另一种方法是使用单个过滤器并检查过滤lambda中是否存在密钥:

List<Employee> result = employees.stream()
    .filter((Employee e) -> {
         return
             (filter.get("department") == null || filter.get("department").equals(e.getDepartment())) &&
             (filter.get("designation") == null || filter.get("designation").equals(e.getDesignation()));
    })
    .collect(Collectors.toList());

编辑:正如评论中所讨论的,考虑将filter.get()的结果存储到临时变量中并直接在过滤lambda中使用。

答案 1 :(得分:0)

我宁愿选择过滤器中的or-condition:

employees.stream()
    .filter(e -> !filter.containsKey("department") || filter.get("department").equals(e.getDepartment()))
    .filter(e -> !filter.containsKey("designation") || filter.get("designation").equals(e.getDesignation()))
    .collect(Collectors.toList());