0

Is it possible to sort employee objects first by their salary and if salaries of two objects are equal, then compare them by name using comparable and comparator interfaces?

For example, I have an Employee class as below

public class Employee{
    private int salary;
    private int name;
    public Employee(salary,name){
        this.salary = salary;
        this.name = name;
    }
    //...........getter methods...........
}

Now suppose we have a list of Employee objects that have some salary amounts and names. I want to use comparator or comparable interface and sort the list in such a way that, list is sorted based on salaries and if salaries are same then in that case those two Employee objects have to be sorted by their names. Can someone please tell me if it is possible? A code snippet would be much appreciated.

2 Answers2

8

Java 8 has made this really easy:

List<Employee> list = ...
list.sort(Comparator.comparing(Employee::getSalary).thenComparing(Employee::getName));
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
0

Yes you can achieve it in 2 steps;

  1. Implement Comparable interface
  2. Provide implementation of int compareTo(Object o) function

    public class Employee implements Comparable{
    
        String name;
        double sal;
    
        //Other implementations
    
        public int compareTo(Object o1) {
    
            Employee e = (Employee)o1;
            int iSalComaprison = Integer.compare(this.sal, e.sal);
            if (iSalComaprison == 0)//Salaries are equal use name as comparison criteria
            {
                //lhs name comparison with rhs name
                return name.compareTo(e.name);
            }
            //Now if salaries are not equal, return comparison of salries
            return iSalComaprison;
    
        }
    
    }
    

You can see first we make comparison on salaries and if they were found equal, we could use names to make a comparison and directly return string comparison results from the if block. If salaries are not equal then we could simply return salary comparison results which we obtained by,

int iSalComaprison = Integer.compare(this.sal, e.sal);

Hope this would help solving your problem using comparator pattern.

A.B.
  • 1,554
  • 1
  • 14
  • 21