Java 8 Comparator keyExtractor [duplicate]

馋奶兔 提交于 2019-12-01 11:58:13

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);

You can use function that extracts a sort key

I.e.

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