Java 8 Comparator keyExtractor [duplicate]

两盒软妹~` 提交于 2019-12-01 11:29:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!