我有一个ArrayList
,它包含一个复杂对象的集合。
该对象有一个日期字段。
我想从这个日期开始整理我的清单。按对象属性排序集合
在示例
class Student{
int ID;
Date joinDate;
}
ArrayList <Student> students;
我如何排序从joinDate
这个学生收集?
我有一个ArrayList
,它包含一个复杂对象的集合。
该对象有一个日期字段。
我想从这个日期开始整理我的清单。按对象属性排序集合
在示例
class Student{
int ID;
Date joinDate;
}
ArrayList <Student> students;
我如何排序从joinDate
这个学生收集?
实现学生类可比接口
然后你要重写以下方法在Student类
public int compareTo(Reminder o) {
return getJoinDate().compareTo(o.getJoinDate());
}
然后,可以使用内置的集合类的排序方法,按日期
你的对象进行排序Collections.sort(students);
实现可比和方法的compareTo
public class Student implements Comparable<Student>{
public int compareTo(Student otherStudent){
// compare the two students here
}
}
Collections.sort(studentsArrayList);
编写Comparator
并将其传递给排序功能。这比改变数据类仅仅提供一种排序要好得多。
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。