按对象属性对集合进行排序

Sort collection by object attribute

我有一个 ArrayList,它包含一个复杂对象的集合。
此对象有一个日期字段。
我想从这个日期开始对我的列表进行排序。

例如

class Student{
 int ID;
 Date joinDate;

}

ArrayList <Student> students;

如何从 joinDate 中对这个学生集合进行排序?

在 Student 中实现 Comparable 接口 class

然后你必须在你的 Student 中覆盖以下方法 class

public int compareTo(Reminder o) {
        return getJoinDate().compareTo(o.getJoinDate());
}

然后使用集合的内置排序方法class按日期对对象进行排序

Collections.sort(students);

实现 Comparable 和方法 compareTo

public class Student implements Comparable<Student>{

    public int compareTo(Student otherStudent){
       // compare the two students here
    }

}

Collections.sort(studentsArrayList);

写一个Comparator传给排序函数。这比更改数据 class 只是为了提供一种排序要好得多。

Collections.sort(students, new Comparator<Student>() {
   public int compare(Student e1, Student e2) {
       return e1.joinDate.compareTo(e2.joinDate);
   }
});

或在 java 8:

Collections.sort(students, (e1, e2) -> e1.joinDate.compareTo(e2.joinDate));

有关详细信息,请查看此 tutorial