gpt4 book ai didi

Java - 用户定义类列表中的搜索条件

转载 作者:行者123 更新时间:2023-12-01 11:57:25 25 4
gpt4 key购买 nike

我有一个 SearchCriteria POJO 类

public class SearchCriteria{

private int empId;
private String empName;
private String empAddress;
private String empDesignation,
:
:
//getter + setters
}

我在其他类中有一个 returnAllEmployees 方法

public List<Employees> returnAllEmployees (){
// makes a db call which has lot of joins and returns info for all the employees
}

现在我的问题是我必须根据传递的搜索条件过滤掉 returnAllEmployees() 的结果,即如果 searchcriteria 的 empName 字段填充为“ABC”,则过滤器列表应包含所有员工的详细信息作为 ABC。

同样,如果搜索条件包含 empName="ABC"和 empDesignation="engineer",则应过滤掉包含名称为 abc 且指定为工程师的所有员工的列表

我知道使用 if-else 是可能的,但这会创建很多行代码

最佳答案

最好的解决方案是使用 Java 8 流。它们非常适合此目的:

List<Employee> listOfEngineersCalledFred = getAllEmployees().stream()
.filter(emp -> emp.getName().equals("Fred"))
.filter(emp -> emp.getDesignation().equals("Engineer"))
.collect(Collectors.toList());

我个人认为有用且巧妙的技术是添加返回谓词的静态方法而不是使用 getter:

class Employee {
public static Predicate<Employee> hasName(String name) {
return emp -> emp.name.equals(name);
}
}

然后可以使用这些来查找所有未调用 Fred 的员工:

streamAllEmployees()
.filter(Employee.hasName("Fred").negate())
...

这看起来比用 getter 暴露字段更整洁、更慎重。

您还可以考虑将 getAllEmployees 转换为 streamAllEmployees:

public Stream<Employee> streamAllEmployees() {
return employeeList.stream();
}

然后您告诉用户他们可以使用列表中的员工对象而不是列表本身来执行操作。

将其作为流返回的好处是,一旦过滤了它,您就可以轻松地对它进行计数、分组、排序、删除重复项、获取前 n 等。如果您正在过滤,您甚至可以轻松地将其转换为使用多个线程大量元素。

例如:

Map<String, Employee> employeesByDesignation = streamAllEmployees()
.collect(Collectors.groupingBy(emp -> emp.getDesignation()));

它们非常强大,值得学习和使用。

关于Java - 用户定义类列表中的搜索条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28248416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com