问题
In Java 8 Comparator, we can create a comparator as follows.
Comparator.comparing(keyExtractor);
Currently I have a class as follows
class Employee {
String name;
Department dept;
}
class Department {
String departmentName;
}
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);
回答1:
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()
Try this out,
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);
回答2:
You can use function that extracts a sort key
I.e.
Comparator.comparing(Employee::getDept,Comparator.comparing(Department::departmentName));
来源:https://stackoverflow.com/questions/49657284/java-8-comparator-keyextractor