Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting of Date ArrayList

I have an ArrayList which contains dates with a format (Satuday,4 Februray 2012). How can I sort this ArrayList ?

like image 571
John Avatar asked Sep 24 '12 08:09

John


2 Answers

This is one of the Simplest way to sort,

Collections.sort(<Your Array List>);
like image 160
Aerrow Avatar answered Nov 15 '22 14:11

Aerrow


If you have any special requirements while sorting, so you may do it by providing your own Comparator. For example:

//your List
ArrayList<Date> d = new ArrayList<Date>();

//Sorting
Collections.sort(d, new Comparator<Date>() {
    @Override
    public int compare(Date lhs, Date rhs) {
        if (lhs.getTime() < rhs.getTime())
            return -1;
        else if (lhs.getTime() == rhs.getTime())
            return 0;
        else
            return 1;
    }
});

The key element is that you are converting your Date object into milliseconds (using getTime()) for comparison.

like image 20
waqaslam Avatar answered Nov 15 '22 15:11

waqaslam