I hava an ArrayList of String values (they need to be formatted as such) which I need to sort by year. The list looks like:
01-05-2011
11-24-2011
01-12-2012
...
I currently have them sorted alphabetically by month, but I was wondering how I can sort this ArrayList of Strings by year.
Collections.sorttakes aComparatorthat specifies how to compare two list values. The list values in your case areStrings. You can just compare the last 4 digits of each string lexicographically and you’re done.Collections.sortis stable, so if your strings are already sorted by month, and you sort by year, groups of strings with the same year will still be sorted by month.Ideally though, you should convert your list to a list of something other than strings, for example, Joda time dates. Right now this code is stringly typed. The sooner you take inputs and coerce them to meaningful objects, the less of your code has to make input assumptions the fewer lines of code you have to debug when your assumptions don’t quite hold.