How to use Java comparator correctly?
•
Java
If I have the following courses:
public class Employee { private int empId; private String name; private int age; public Employee(int empId,String name,int age) { // set values on attributes } // getters & setters }
How do I use a comparator by name, then age, then ID?
Solution
You need to implement it to sort by preferred elements That is, you need to compare by name, and then if the comparison is equal, compare by age, etc An example is listed below:
public class EmployeeComparator implements Comparator<Employee> { @Override public int compare(Employee e1,Employee e2) { int nameDiff = e1.getName().compareTo(e2.getName()); if(nameDiff != 0) { return nameDiff; } int ageDiff = e1.getAge() - e2.getAge(); if(ageDiff != 0) { return ageDiff; } int idDiff = e1.getEmpId() - e2.getEmpId(); return idDiff; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码