I have a block of data, and I want to sort them according to age and salary.
Object Employee has:
- Name
- Designation
- Age
- Salary
I want to sort then so that the max age will be on top. But if the age is same of two persons,then it will compare the salary between them, and then for whom Age and Salary is high, he will be on top of the ArrayList.
Here in the top list accordingly: Bob, Tim, Tom. then in the list: Alex, Sam, Craig and so on.
List<Employee> listEmployees = new ArrayList<Employee>();
listEmployees.add(new Employee("Tom", "Developer", 45, 80000));
listEmployees.add(new Employee("Sam", "Designer", 30, 75000));
listEmployees.add(new Employee("Bob", "Designer", 45, 134000));
listEmployees.add(new Employee("Peter", "Programmer", 25, 60000));
listEmployees.add(new Employee("Tim", "Designer", 45, 130000));
listEmployees.add(new Employee("Craig", "Programmer", 30, 52000));
listEmployees.add(new Employee("Anne", "Programmer", 25, 51000));
listEmployees.add(new Employee("Alex", "Designer", 30, 120000));
I have tried using
Collections.sort(Employees , new Comparator<listEmployees >() {
@Override
public int compare(EmployeeModelCls lhs, EmployeeModelCls rhs) {
return (rhs.getAge() - lhs.getAge());
}
});
also I have tried
Collections.sort(Employees , new Comparator<listEmployees >() {
@Override
public int compare(EmployeeModelCls lhs, EmployeeModelCls rhs) {
return ((rhs.getAge() - lhs.getAge()) - (rhs.getSalary() - lhs.getSalary()));
}
});
but unable to get correct data. Does anybody have any ideas?
-? Try to use compareTo(...)