[英]Sorting and Filtering List of Objects
我正在接受外部服务,从中获取组织的所有员工详细信息,如下所示。 我正在使用java8和spring cloud feign客户端来使用该服务
[
{
"employee": {
"empId": "empId123",
"name": "Emp1",
"houseNumber": "5",
"firstName": "firstName1",
"lastName": "lastName1",
"city": "city1",
"band": "A"
},
"type": "ABC"
},
{
"employee": {
"empId": "empId456",
"name": "Emp2",
"houseNumber": "7",
"firstName": "firstName2",
"lastName": "lastName2",
"city": "city2",
"band": "B"
},
"type": "ABC"
}
:
:
]
员工详细信息服务有大约10000多个员工详细信息。
我需要创建另外两个服务
目前我使用的排序服务如下所示
final List<Employees> employeesList = employeeService.getAllEmployees().stream()
.sorted((emp1, emp2) -> p1.getAddress().getCity().compareTo(emp2.getAddress().getCity()))
.sorted((emp1, emp2) -> p1.getAddress().getHouseNumber().compareTo(emp2.getAddress().getHouseNumber()))
.collect(Collectors.toList());
对于过滤我使用以下代码
String cityName = "some city name"...
final List<Employees> employeesfilteredList = employeeService.getAllEmployees()
.stream()
.filter(employee -> employee.getAddress().getCity().equalsIgnoreCase(cityName == null ? "" : cityName))
.collect(Collectors.toList());
但是我的客户是一个技术人员说这有性能问题,并要求带来一些时间复杂度较低的东西(最好是O(1) )来带来结果
任何人都可以告诉我当前使用的方法有什么问题,有什么方法可以用其他任何方式或方法即兴表达它
有一件事我能想到的,你肯定能凑合是呼叫sorted
的两倍,可只有一次:
// replacing with 'employees' for 'employeeService.getAllEmployees()'
Comparator<Employees> compareBasedOnCity =
Comparator.comparing(emp -> emp.getAddress().getCity());
Comparator<Employees> compareBasedOnHouse =
Comparator.comparing(emp -> emp.getAddress().getHouseNumber());
employees.sort(compareBasedOnCity.thenComparing(compareBasedOnHouse));
过滤器期间的另一个是避免将null
和""
字符串视为相同:
List<Employees> finalList = employees.stream()
.filter(employee -> employee.getAddress().getCity().equalsIgnoreCase(cityName))
// don't consider empty city name same as null (think of " " otherwise)
.collect(Collectors.toList());
但是,正如Holger和JB Nizet已经指出的那样,这并没有像你期望的那样降低从O(nlogn)
到O(1)
的复杂性。
进一步与Access,Insertion和Deletion等操作进行比较也不相同。 由于执行的操作也是不同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.