Ordering by date. Comparator. Java

26,399

Solution 1

The natural order on dates (as defined by compareTo) is that the later date is "greater than" the earlier one. For seniority the person who has been there the longer is more senior, i.e. you want the earlier start date to signify greater seniority than the later one.

Since the contract of Comparator states that if compare(a,b) != 0 then compare(a,b) and compare(b,a) must have opposite sign, you have two choices for how to implement a reverse ordered comparison of 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 comparator results is whether they are >, < or == to 0 - while many examples use -1, 0 and +1 any value with the right sign is fine.

Solution 2

If you want to change the sort order then use:

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

Don't play with the Comparator.

Share:
26,399
Rollerball
Author by

Rollerball

Updated on April 03, 2020

Comments

  • Rollerball
    Rollerball about 4 years

    the next snippet taken from this java tutorial, compares the second argument object to the first one rather than viceversa. *The method hireDate() returns a Date object signifying the hiring date of that 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 the java tutorial explanation:

    Note that the Comparator passes the hire date of its second argument to its first rather than vice versa. The reason is that the employee who was hired most recently is the least senior; sorting in the order of hire date would put the list in reverse seniority order.

    Still I do not get why by inverting e1 and e2 in compareTo it should solve the issue.

    Any further clarification?

    Thanks in advance.