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);
以上是常用的幾種集合排序的實現方式。具體選擇哪種方式取決于需要排序的集合類型和排序規則的復雜程度。