Java集合的排序可以通过以下几种方式实现:
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(3);
list.add(9);
Collections.sort(list); // 默认按照升序排序
System.out.println(list); // 输出:[3, 5, 9]
int[] array = {5, 3, 9};
Arrays.sort(array); // 默认按照升序排序
System.out.println(Arrays.toString(array)); // 输出:[3, 5, 9]
class Student implements Comparable<Student> {
private String name;
private int score;
// 省略构造方法和其他方法
@Override
public int compareTo(Student o) {
return this.score - o.score; // 按照分数升序排序
}
}
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 85));
students.add(new Student("Bob", 92));
students.add(new Student("Charlie", 78));
Collections.sort(students); // 按照分数升序排序
System.out.println(students);
class ScoreComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getScore() - s2.getScore(); // 按照分数升序排序
}
}
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 85));
students.add(new Student("Bob", 92));
students.add(new Student("Charlie", 78));
Collections.sort(students, new ScoreComparator()); // 按照分数升序排序
System.out.println(students);
以上是常用的几种集合排序的实现方式。具体选择哪种方式取决于需要排序的集合类型和排序规则的复杂程度。