Sort objects in ArrayList by date?
You can make your object comparable:
public static class MyObject implements Comparable<MyObject> { private Date dateTime; public Date getDateTime() { return dateTime; } public void setDateTime(Date datetime) { this.dateTime = datetime; } @Override public int compareTo(MyObject o) { return getDateTime().compareTo(o.getDateTime()); }}
And then you sort it by calling:
Collections.sort(myList);
However sometimes you don't want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:
Collections.sort(myList, new Comparator<MyObject>() { public int compare(MyObject o1, MyObject o2) { return o1.getDateTime().compareTo(o2.getDateTime()); }});
However, the above works only if you're certain that dateTime is not null at the time of comparison. It's wise to handle null as well to avoid NullPointerExceptions:
public static class MyObject implements Comparable<MyObject> { private Date dateTime; public Date getDateTime() { return dateTime; } public void setDateTime(Date datetime) { this.dateTime = datetime; } @Override public int compareTo(MyObject o) { if (getDateTime() == null || o.getDateTime() == null) return 0; return getDateTime().compareTo(o.getDateTime()); }}
Or in the second example:
Collections.sort(myList, new Comparator<MyObject>() { public int compare(MyObject o1, MyObject o2) { if (o1.getDateTime() == null || o2.getDateTime() == null) return 0; return o1.getDateTime().compareTo(o2.getDateTime()); }});
Since Java 8 the List interface provides the sort method. Combined with lambda expression the easiest solution would be
// sort DateTime typed listlist.sort((d1,d2) -> d1.compareTo(d2));// or an object which has an DateTime attributelist.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));// or like mentioned by Tunakilist.sort(Comparator.comparing(o -> o.getDateTime()));
Reverse sorting
Java 8 comes also with some handy methods for reverse sorting.
//requested by lilylist.sort(Comparator.comparing(o -> o.getDateTime()).reversed());
You can use Collections.sort method. It's a static method. You pass it the list and a comparator. It uses a modified mergesort algorithm over the list. That's why you must pass it a comparator to do the pair comparisons.
Collections.sort(myList, new Comparator<MyObject> { public int compare(MyObject o1, MyObject o2) { DateTime a = o1.getDateTime(); DateTime b = o2.getDateTime(); if (a.lt(b)) return -1; else if (a.lteq(b)) // it's equals return 0; else return 1; }});
Note that if myList is of a comparable type (one that implements Comparable interface) (like Date, Integer or String) you can omit the comparator and the natural ordering will be used.