根据某些条件添加过滤器java 8

San*_*waj 4 stream java-8

我需要根据一些参数(如名字、姓氏等)过滤员工列表。这些参数是用户定义的,用户可以选择所有过滤器或过滤器组合。

public List<Employee> getFilterList(String firstName,String lastName)
{
    List<Employee> empList = empRepository.getEmployees();

    Stream<Employee> empStream=empList.stream();

   if(firstName!=null)
   {
     empStream= empStream.filter(e-> e.getFirstname().equals(firstName))
   }

   if(lastName!=null)
   {
     empStream= empStream.filter(e-> e.getlastName().equals(lastName))
   }

   return empStream.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)

这是这样做的正确方法吗?

注意:上面的代码工作正常,我只是在寻找另一种更好的方法(如果有的话)。

案例一: getFilterList(null,null)返回所有员工名单

情况 2: getFilterList("abc",null)返回名字为 abc 的所有员工的列表。

zho*_*xin 5

empList根据过滤器的参数显示列表firstName或根据参数过滤lastName,代码模式几乎相同。所以我想出了以下代码。

public List<Employee> getFilterList(String firstName,String lastName){

    List<Employee> empList = empRepository.getEmployees();

    return empList.stream().filter(getPredicateBiFun.apply(firstName,Employee::getFirstName))
                           .filter(getPredicateBiFun.apply(lastName,Employee::getLastName))
                           .collect(Collectors.toList());

}
Run Code Online (Sandbox Code Playgroud)

看起来更像是Java8风格。这里有一个静态属性,getPredicateBiFun你可以看到它可以Predicate<Employee>根据参数得到相应的表达式。所以这只是BiFunction我们想要的一个很好的模式。

private static BiFunction<String, Function<Employee, String>, Predicate<Employee>> getPredicateBiFun = (name, getNameFun) -> employee -> name == null ? true : name.equals(getNameFun.apply(employee));
Run Code Online (Sandbox Code Playgroud)

就这样 :)