2015-05-01 200 views
1

我有一個ArrayList,它包含一個複雜對象的集合。
該對象有一個日期字段。
我想從這個日期開始整理我的清單。按對象屬性排序集合

在示例

class Student{ 
int ID; 
Date joinDate; 

} 

ArrayList <Student> students; 

我如何排序從joinDate這個學生收集?

回答

1

實現學生類可比接口

然後你要重寫以下方法在Student類

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

然後,可以使用內置的集合類的排序方法,按日期

你的對象進行排序
Collections.sort(students); 
0

實現可比和方法的compareTo

public class Student implements Comparable<Student>{ 

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

} 

Collections.sort(studentsArrayList); 
0

編寫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