您可以使用Collections.sort 方法接受comparator 作为其第二个参数。传入一个comparator,它定义了你想要的顺序。例如,给定一个Student 类,您可以使用Collections.sort 和自定义comparator 按名称升序排列Student,如下所示:
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
class Student {
private final String name;
private final int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
@Override
public String toString() {
return "Student [name=" + name + ", score=" + score + "]";
}
public static void main(String[] args) {
List<Student> list = new LinkedList<>(
Arrays.asList(new Student("David", 3), new Student("Alice", 3), new Student("Thomas", 9)));
System.out.println("Before Sort: " + list);
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareTo(o2.getName());
}
});
System.out.println("After Sort: " + list);
}
}
这将产生输出
before: [Student [name=David, score=3], Student [name=Alice, score=3], Student [name=Thomas, score=9]]
after: [Student [name=Alice, score=3], Student [name=David, score=3], Student [name=Thomas, score=9]]