2 回答

TA貢獻1862條經(jīng)驗 獲得超7個贊
您使用另Collections.sort一種方法:sort(List<T> list, Comparator<? super T> c)
你像這樣使用它:
Collections.sort(classRoll, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2.getName());
}
});
在 Java 8+ 中,它更容易:
// Sort by name
classRoll.sort(Comparator.comparing(Student::getName));
// Sort by GPA
classRoll.sort(Comparator.comparingDouble(Student::getGpa));
如果名稱是 2 個字段(firstName和lastName),則可以使用thenComparing:
// Sort by last name, then first name
classRoll.sort(Comparator.comparing(Student::getLastName)
.thenComparing(Student::getFirstName));

TA貢獻1895條經(jīng)驗 獲得超7個贊
這樣做的方法是使用Collections.sort自定義比較器:
Comparator<Student> nameComparator = new Comparator<Student>() {
public int compare(Student student1, Student student2) {
return student1.getName().compareTo(student2.getName());
}
};
Comparator<Student> gpaComparator = new Comparator<Student>() {
public int compare(Student student1, Student student2) {
return student1.getGPA().compareTo(student2.getGPA());
}
};
然后您可以根據(jù)需要使用不同的比較器:
Collections.sort(classRoll, nameComparator);
通過這種方式,與上面具有 2 個循環(huán)的解決方案相比,您擁有一個優(yōu)化的分揀機。
添加回答
舉報