The default ordering of Date
will put newer dates after older dates so the oldest dates would be at the beginning of your list and the newest dates at the end. Comparators
have always been hard to read in my opinion so I have switched to using google's Ordering
objects that implement Comparator
a little cleaner. For example your Comparator
could be written like this:
Ordering<SomeObject> order = Ordering.natural().onResultOf(new Function<SomeObject, Date>() {
public Date apply(SomeObject object) {
return object.getDate();
}
});
Comparator<SomeObject> comparator = order; // Ordering implements Comparable so this would be legal to do
Collections.sort(someList, order);
The order Comparator that this code created would sort SomeObject objects based on their Date
using the Date
's natural ordering. But what makes Ordering
really nice is some of extra methods change the order without having to write any more logic, for example to reverse the order of dates to be newest to oldest you just have to add a call to reverse():
Ordering<SomeObject> order = Ordering.natural().reverse().onResultOf(new Function<SomeObject, Date>() {
public Date apply(SomeObject object) {
return object.getDate();
}
});