您可以使用自定义Comparator。
这是一个完整的例子(不包括进口):
public class Main {
// main method setting up and printing students
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
Student s1 = new Student();
s1.setScore(90);
s1.setFirstName("abc");
students.add(s1);
Student s2 = new Student();
s2.setScore(95);
s2.setFirstName("def");
students.add(s2);
Student s3 = new Student();
s3.setScore(85);
s3.setFirstName("xyz");
students.add(s1);
System.out.printf("Unordered: %s%n", students);
// sorting using anonymous Comparator
Collections.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
// notice the cast to (Integer) to invoke compareTo
return ((Integer)s1.getScore()).compareTo(s2.getScore());
}
});
System.out.printf("Ordered: %s%n", students);
}
// Student class
static class Student {
private int score;
private String firstName;
// boring stuff
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String name) {
this.firstName = name;
}
// for printing
@Override
public String toString() {
return String.format("Student \"%s\" with score: %d%n", firstName,
score);
}
}
}
输出
Unordered: [Student "abc" with score: 90
, Student "def" with score: 95
, Student "abc" with score: 90
]
Ordered: [Student "abc" with score: 90
, Student "abc" with score: 90
, Student "def" with score: 95
]
注意
正如其他人提到的,如果唯一(或默认)排序将按分数排序,您也可以在您的 Student 班级中 implement Comparable<Student>。#
第二次修改
为了按降序排序,您可以将Comparator 中的return 语句替换为以下内容:
return ((Integer)s2.getScore()).compareTo(s1.getScore());
感谢 programminglover 发现这一点/为错误地拒绝编辑表示歉意!