Sort objects in ArrayList by date?

后端 未结 14 2160
生来不讨喜
生来不讨喜 2020-11-22 06:58

Every example I find is about doing this alphabetically, while I need my elements sorted by date.

My ArrayList contains objects on which one of the datamembers is a

14条回答
  •  -上瘾入骨i
    2020-11-22 07:04

    Since Java 8 the List interface provides the sort method. Combined with lambda expression the easiest solution would be

    // 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()));
    

    Reverse sorting

    Java 8 comes also with some handy methods for reverse sorting.

    //requested by lily
    list.sort(Comparator.comparing(o -> o.getDateTime()).reversed());
    

提交回复
热议问题