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

在Java中,Collections.sort() 是一个非常常用的方法,用于对列表(List)中的元素进行排序。它位于 java.util.Collections 工具类中,支持对实现了 Comparable 接口的元素进行自然排序,也支持通过自定义 Comparator 实现灵活排序。
对于像 Integer、String 这样的内置类型,它们已经实现了 Comparable 接口,可以直接使用 Collections.sort() 进行升序排序。
示例:
List<Integer> numbers = new ArrayList<>();字符串列表同理,会按字典顺序排序:
立即学习“Java免费学习笔记(深入)”;
List<String> words = Arrays.asList("banana", "apple", "cherry");如果你有一个自定义类,比如 Student,可以通过实现 Comparable<Student> 接口来定义默认排序规则(如按分数排序)。
class Student implements Comparable<Student> {使用方式:
List<Student> students = new ArrayList<>();如果不想修改类本身,或需要多种排序方式,可以传入 Comparator 作为参数。
例如,按学生姓名排序:
Collections.sort(students, new Comparator<Student>() {使用 Lambda 表达式更简洁(Java 8+):
Collections.sort(students, (s1, s2) -> s1.name.compareTo(s2.name));按分数降序:
Collections.sort(students, (s1, s2) -> Integer.compare(s2.score, s1.score));例如:
Collections.sort(numbers, Collections.reverseOrder()); // 降序排列基本上就这些。掌握自然排序和自定义比较器的使用,就能应对大多数排序场景了。
以上就是Java中Collections.sort排序列表使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号