Possible Duplicate:
sort array list of special strings, by date
I have an ArrayList of Strings that read in from a file and the first part of each string is a date ex: 12/01/2012. When I use Collections.sort(); it sorts it fine within the year from oldest to newest, but when it gets to 01/01/2013 it throws that up on the top of the list with the oldest. How can I get it to use the year as part of the sort? I tried using Date, but it did the same. Each string has a lot of info I would like to keep in it and just sort it by the beginning. I see no need to post code since it’s working and all I’m having trouble with is just sorting. I’ve searched on here for awhile and tried a few different sorting options to no avail. So I must be confused or forgetting something. If anyone has any ideas how to sort Strings with dates in the beginning please help! Thanks!
example string: “12/01/2012 34023843 Item Number”
You need a custom comparator. Comparing strings in natural order (ie, using the fact that
StringimplementsComparable<String>) will give the result you see, since0is lower than1, so this is expected.Here is an example class which can do what you want, but note that it assumes all dates are correctly formatted (the
parse()method ofDateFormatthrows an uncheckedIllegalArgumentExceptionif the date is incorrect):You can then use
Collections.sort(theArray, MyComparator.getInstance());