How to perform sorting based on Comparator keeping original sort intact in Java -
i've been going through implementation examples of comparable vs comparator interface.
but, i've been stuck @ 1 point in it's implementation :
suppose, i've simple class : employee has default sorting mechanism based on employee name.
public class employee implements comparable<employee> { private int empsalary; private string empname; @override public int compareto(employee e) { return this.empname.compareto(e.empname); } }
but, let's say, i've sort based on employee name first, , if 2 employess have same name, i've sort them according salary.
so, wrote custom comparator sort based on salary below
public class salarycomparator implements comparator<employee> { @override public int compare(employee e1, employee e2) { return e1.empsalary - e2.empsalary; } }
but, when ran test class sort based on name first, salary second, output not expected.
collections.sort(employeelist, new salarycomparator());
input order :
name : kumar, salary : 40 name : sanket, salary : 10 name : kumar, salary : 20
expected output :
name : kumar, salary : 20 name : kumar, salary : 40 name : sanket, salary : 10
actual output :
name : sanket, salary : 10 // incorrect order name : kumar, salary : 20 name : kumar, salary : 40
this not because employee
class has default ordering, using collections.sort
custom comparator introduce new layer of ordering.
for example let's default ordering of employees
salary in ascending order. let's want sort them salary in descending order.
according logic how behave?
collections.sort(employees, new salarydescendingcomparator());
the fact when provide custom comparator collections.sort
, use 1 , not sorting mechanism implemented in employee
class.
as doc states:
sorts specified list according order induced specified comparator.
so because salarycomparator
compares employees salary, that's why output.
if want sort name first , salary, you'll have in 1 time, i.e :
public class employee implements comparable<employee> { private int empsalary; private string empname; @override public int compareto(employee e) { int cmp = this.empname.compareto(e.empname); return cmp != 0 ? cmp : integer.compare(empsalary, e.empsalary); } }
Comments
Post a Comment