Order by date. Comparator Java

the following snippet taken from this java tutorial compares the second argument with the first, and not vice versa. * The hireDate () method returns a Date object that indicates the hiring date of this particular employee.

import java.util.*; public class EmpSort { static final Comparator<Employee> SENIORITY_ORDER = new Comparator<Employee>() { public int compare(Employee e1, Employee e2) { return e2.hireDate().compareTo(e1.hireDate()); } }; 

Here is a java tutorial explanation:

Note that the comparator passes the lease date of the second argument to its first, and not vice versa. The reason is that the employee who was hired most recently is the least senior; sorting in the order of the date of employment will put the list in the order of the length of service.

However, I do not understand why, by inverting e1 and e2 to compareTo , it should solve the problem.

Any further clarification?

Thanks in advance.

+4
source share
3 answers

The natural order in dates (as defined by compareTo ) is that a later date is "greater than the previous". For seniority, a person who has been there longer is older, i.e. You want an earlier start date to mean a longer experience than a later one.

Since the Comparator contract states that if compare(a,b) != 0 , then compare(a,b) and compare(b,a) should have the opposite sign, you have two options for how to implement the reverse ordered comparison a and b - either return -(a.compareTo(b)) or b.compareTo(a) - they are guaranteed to have the same sign.

They will not necessarily have the same value, but the only thing that matters for the results of the comparator is whether they are > , < or == equal to 0, and in many examples -1 , 0 and +1 any value with the correct icon well.

+6
source

If you want to change the sort order, use:

 Collections.sort(list, Collections.reverseOrder(comparator)); 

Do not play with the comparator.

+7
source

The compare comparator calculates to return -1, 0 or 1 if e1<e2 , e1==e2 or e1>e2 . So if the final order you get is just the opposite of what you want, just invert a and b, solves the problem.

0
source

All Articles