Basically I have an employees array that has commission, salary, and hourly employees. I need to display an alphabetized list of the employees. If the last names are the same the first names also need to be alphabetized. How do I go about doing this.
Arrays.sort(employees, new Comparator<Employee>() {
public int compare(Employee a, Employee b) {
int cmp = a.getLastName().compareTo(b.getLastName());
if (cmp == 0) {
cmp = a.getFirstName().compareTo(b.getFirstName());
}
return cmp;
}
});
Or, using Guava to get something more readable and less bug-prone,
Arrays.sort(employees, new Comparator<Employee>() {
public int compare(Employee a, Employee b) {
return ComparisonChain.start()
.compare(a.getLastName(), b.getLastName())
.compare(a.getFirstName(), b.getFirstName())
.result();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.