Java 8 Comparator keyExtractor [英] Java 8 Comparator keyExtractor
问题描述
在Java 8 Comparator中,我们可以按如下方式创建一个比较器。
In Java 8 Comparator, we can create a comparator as follows.
Comparator.comparing(keyExtractor);
目前我有一个课程如下
class Employee {
String name;
Department dept;
}
class Department {
String departmentName;
}
现在,如果我想为Employee类创建一个比较器来对记录进行排序根据部门名称,我如何编写我的密钥提取器?
Now, if I want to create a comparator for Employee class which sorts the records based on the department name, how can I write my key extractor?
尝试下面的代码,但没有用。
Tried the below code, but did not work.
Comparator.comparing(Employee::getDept::getDepartmentName);
推荐答案
这里的诀窍是方法引用不是对象而是没有会员可以访问。所以你不能这样做:
The trick here is method references are not objects and don't have members to access. So you can't do this:
Employee::getDept.getDepartmentName
此外,方法引用不是类,因此您无法从它们获取另一个方法引用。所以这也失败了。
Moreover, method references are not classes, so you can't get another method reference from them. So this also fails.
Employee::getDept::getDepartmentName
最后,我们留下的唯一选择就是这个。
Finally, the only option that is left with us is this.
e -> e.getDept().getDepartmentName()
试试这个,
Employee empOne = new Employee("Mark", new Department("Accounts"));
Employee empTwo = new Employee("Melissa", new Department("Sales"));
List<Employee> employees = Arrays.asList(empOne, empTwo);
employees.sort(Comparator.comparing(e -> e.getDept().getDepartmentName()));
employees.forEach(System.out::println);
这篇关于Java 8 Comparator keyExtractor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!