Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort date in descending order using comparator

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

like image 934
jaggs Avatar asked Nov 29 '22 11:11

jaggs


1 Answers

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.
like image 198
Jon Skeet Avatar answered Dec 11 '22 05:12

Jon Skeet