Collections.sort(
myList, new Comparator<String>() {
@Override
public int compare(String a, String b) {
// If a is "11-24-2012", then aLastDash points
// here ---------^.
int aLastDash = a.lastIndexOf("-");
int bLastDash = b.lastIndexOf("-");
return a.substring(aLastDash+1).compareTo(
b.substring(bLastDash+1));
}
});
Collections.sort
takes a Comparator
that specifies how to compare two list values. The list values in your case are String
s. You can just compare the last 4 digits of each string lexicographically and you're done.
Collections.sort
is 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.