Sort Date ArrayList

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

+6
source share
2 answers

This is one of the easiest ways to sort,

 Collections.sort(<Your Array List>); 
+14
source

If you have special sorting requirements, you can do this by providing your own Comparator . For instance:

 //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 converting your Date object to milliseconds (using getTime() ) for comparison.

+5
source

Source: https://habr.com/ru/post/926091/


All Articles