[英]Multi-Level Comparator
Please can you show me the simplest way to implement multi-level comparator: I have an employee class and I want to compare them by salary, this is done by implementing a comparator :请你告诉我实现多级比较器的最简单方法:我有一个员工类,我想按薪水比较它们,这是通过实现一个比较器来完成的:
public class SalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
return (int) (o1.getSalary()-o2.getSalary());
}
}
Now if the salary is the same I want to compare them by Lastname or ID现在,如果薪水相同,我想通过姓氏或 ID 比较它们
How can I do it ?我该怎么做 ?
Thank you谢谢
You can use the Comparator.thenComparing
method.您可以使用Comparator.thenComparing
方法。 The Comparator.comparing
method also simplifies this so you don't have to write your own classes implementing Comparator
: Comparator.comparing
方法也简化了这一点,因此您不必编写自己的类来实现Comparator
:
Comparator<Employee> cmp = new SalaryComparator()
.thenComparing(Comparator.comparing(Employee::getLastName))
.thenComparing(Comparator.comparing(Employee::getID));
You can even eliminate your SalaryComparator
class entirely:你甚至可以完全消除你的SalaryComparator
类:
Comparator<Employee> cmp = Comparator.comparing(Employee::getSalary)
.thenComparing(Comparator.comparing(Employee::getLastName))
.thenComparing(Comparator.comparing(Employee::getID));
If your methods return primitive types (eg if getSalary
returns double
), use eg the comparingDouble
method instead of comparing
.如果你的方法返回原始类型(例如,如果getSalary
返回double
),例如使用的comparingDouble
,而不是方法comparing
。 There are also comparingInt
and comparingLong
.还有comparingInt
和comparingLong
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.