Collections.sort()用于对List排序,支持自然排序和自定义Comparator;可对Integer、String等实现Comparable的类型排序,也可通过Comparable接口或Comparator对自定义对象如Student按属性排序,使用Lambda更简洁,并需注意列表非null、无null元素及使用稳定排序算法。

在Java中,Collections.sort() 是一个非常常用的方法,用于对列表(List)中的元素进行排序。它位于 java.util.Collections 工具类中,支持对实现了 Comparable 接口的元素进行自然排序,也支持通过自定义 Comparator 实现灵活排序。
1. 对基本类型包装类排序
对于像 Integer、String 这样的内置类型,它们已经实现了 Comparable 接口,可以直接使用 Collections.sort() 进行升序排序。
示例:
Listnumbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
Collections.sort(numbers);
System.out.println(numbers); // 输出: [1, 2, 5, 8]
字符串列表同理,会按字典顺序排序:
立即学习“Java免费学习笔记(深入)”;
ListCollections.sort(words);
System.out.println(words); // 输出: [apple, banana, cherry]
2. 对自定义对象排序(实现 Comparable)
如果你有一个自定义类,比如 Student,可以通过实现 Comparable
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.score, other.score); // 按分数升序
}
}
使用方式:
students.add(new Student("Alice", 85));
students.add(new Student("Bob", 72));
students.add(new Student("Charlie", 90));
Collections.sort(students);
// 将按 score 升序排列
3. 使用 Comparator 自定义排序规则
如果不想修改类本身,或需要多种排序方式,可以传入 Comparator 作为参数。
例如,按学生姓名排序:
Collections.sort(students, new Comparator@Override
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
});
使用 Lambda 表达式更简洁(Java 8+):
Collections.sort(students, (s1, s2) -> s1.name.compareTo(s2.name));按分数降序:
Collections.sort(students, (s1, s2) -> Integer.compare(s2.score, s1.score));4. 注意事项和建议
- 列表必须是可变的且支持随机访问(如 ArrayList),不能是 null 或不可修改列表。
- 排序前确保列表中没有 null 元素,否则可能抛出 NullPointerException。
- Collections.sort() 使用的是稳定的排序算法(归并排序或优化的快速排序),相同元素的相对位置不会改变。
- 若需逆序,可使用 Collections.reverseOrder() 获取逆序比较器。
例如:
Collections.sort(numbers, Collections.reverseOrder()); // 降序排列基本上就这些。掌握自然排序和自定义比较器的使用,就能应对大多数排序场景了。










