Sort an Employee Object list first by salary and if salaries are equal, then by name

We Are Going To Discuss About Sort an Employee Object list first by salary and if salaries are equal, then by name . So lets Start Sort an Employee Object list first by salary and if salaries are equal, then by name Java Article.

Sort an Employee Object list first by salary and if salaries are equal, then by name

  1. Sort an Employee Object list first by salary and if salaries are equal, then by name

    Java 8 has made this really easy:
    List<Employee> list = ... list.sort(Comparator.comparing(Employee::getSalary).thenComparing(Employee::getName));

  2. Sort an Employee Object list first by salary and if salaries are equal, then by name

    Java 8 has made this really easy:
    List<Employee> list = ... list.sort(Comparator.comparing(Employee::getSalary).thenComparing(Employee::getName));

Solution 1

Java 8 has made this really easy:

List<Employee> list = ...
list.sort(Comparator.comparing(Employee::getSalary).thenComparing(Employee::getName));

Original Author Lukas Eder Of This Content

Solution 2

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.

Original Author A.B. Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment