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());
}
}
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject o1, MyObject o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
Collections.sort(dataVector, new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
return ((Date)o1[0]).compareTo(((Date)o2[0]));
}
});
ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();
地图对象如下:
Map<String, Object> map = new HashMap<>();
// of course this is the actual formatted date below in the timestamp
map.put("timestamp", "MM/dd/yyyy HH:mm:ss");
map.put("item1", "my text goes here");
map.put("item2", "my text goes here");
// sort DateTime typed list
list.sort((d1,d2) -> d1.compareTo(d2));
// or an object which has an DateTime attribute
list.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));
// or like mentioned by Tunaki
list.sort(Comparator.comparing(o -> o.getDateTime()));
反向排序
Java8还提供了一些方便的反向排序方法。
//requested by lily
list.sort(Comparator.comparing(o -> o.getDateTime()).reversed());