how to sort date in descending order using comparator

34,316

Solution 1

But i couldn't able to sort the date in descending order.

Two easy options:

  • You could just reverse your comparison yourself, using secondDate.compareTo(firstDate). (I assume that in your real code you're actually returning retVal; it's ignored in your posted code.)
  • Call Collections.reverseOrder(Comparator) to create a comparator with the reverse order of the original one.

Solution 2

Instead of comparing firstDate against secondDate, compare secondDate against firstDate:

retVal = secondDate.compareTo(firstDate);

And don't forget to return retVal instead of 0 ;)

Share:
34,316
jaggs
Author by

jaggs

Updated on June 07, 2020

Comments

  • jaggs
    jaggs almost 4 years

    I have a bean object testBean with getter setter and methods.I am retrieving the results from the database and storing it in a TreeMap

    The Output of the Map will look like this:

    {Student1 = [testBean[Dept=Science,ID=12,grade=A,Date=12-Jan-2013]]
                [testBean[Dept=Science,ID=12,grade=B,Date=14-Mar-2013]]
    
    {Student2 = [testBean[Dept=Science,ID=02,grade=A,Date=12-Jan-2013]]
                [testBean[Dept=Science,ID=02,grade=A,Date=14-Mar-2013]]
    

    I need the Output to be arranged in Descending order so that the latest date comes first. So I am using a comparator to sort the date:

    public int DateCompare(Object studentObj, Object anotherStudentObj) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
        String value = ((testBean) studentObj).getDateTmTrans();
        String value1 = ((testBean) anotherStudentObj).getDateTmTrans();
        int retVal = 0;
    
        try {
    
            Date firstDate = dateFormat.parse(value);
            Date secondDate = dateFormat.parse(value1);     
            retVal = firstDate.compareTo(secondDate);
    
        } catch (ParseException e) {
            e.printStackTrace();
        }       
        return 0;
    }
    

    But I couldn't able to sort the date in descending order. Is there any solution to get the desired output?

    Any suggestions are welcome

    Thanks in advance