【问题标题】:Using Java8 to filter with multiple attributes only if they are not null仅当它们不为空时才使用 Java8 过滤多个属性
【发布时间】:2016-04-28 02:25:31
【问题描述】:

我有一个这样的对象

public class Organization {

  private List<Employee> employees;

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

我有一个接受Map&lt;String, Object&gt; 的搜索方法。此映射可以包含部门或名称的键值或两者。

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

这是我需要做的。如果部门键存在,我需要返回该部门的所有员工。如果部门和指定键存在,我需要返回符合这两个条件的所有员工。我该怎么做?

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

【问题讨论】:

  • 从你所说的看来,部门总是存在的。唯一可选的名称?

标签: java-8


【解决方案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());

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

【讨论】:

  • 程序逻辑没问题,但要避免多余的get调用……
  • @Holger:你说得对,这值得。我想通过定义新变量来避免过多地扩展代码,因此概念部分仍然简单明了且易于理解。
【解决方案2】:

我宁愿在过滤器中使用或条件:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2016-08-29
    • 2016-02-29
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多