Question:
There is an Employee
class in which there is an ArrayList<Employee>
, you need to sort the employees in the list by ЗП
, and if the ЗП
is the same after the name. I know how to sort by ЗП
, but I can’t figure out how to sort with an equal ЗП
after the name. Thanks in advance. Can you at least give me a hint.
Answer:
Suppose we have a class
class Employee {
String name;
double salary;
}
and variable
ArrayList<Employee> employees;
You can sort, for example, in the following way:
Collections.sort(
employees,
new Comparator<Employee>() {
public int compare(final Employee e1, final Employee e2) {
if (e1.salary < e2.salary)
return -1;
if (e2.salary > e2.salary)
return 1;
return e1.name.compareTo(e2.name);
}
}
);