Sort objects in ArrayList by date?

后端 未结 14 2434
生来不讨喜
生来不讨喜 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条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 07:08

    Given MyObject that has a DateTime member with a getDateTime() method, you can sort an ArrayList that contains MyObject elements by the DateTime objects like this:

    Collections.sort(myList, new Comparator() {
        public int compare(MyObject o1, MyObject o2) {
            return o1.getDateTime().lt(o2.getDateTime()) ? -1 : 1;
        }
    });
    

提交回复
热议问题