首页 > Java > java教程 > 正文

Java中Collections.sort排序列表使用

P粉602998670
发布: 2025-10-04 16:01:02
原创
731人浏览过
Collections.sort()用于对List排序,支持自然排序和自定义Comparator;可对Integer、String等实现Comparable的类型排序,也可通过Comparable接口或Comparator对自定义对象如Student按属性排序,使用Lambda更简洁,并需注意列表非null、无null元素及使用稳定排序算法。

java中collections.sort排序列表使用

在Java中,Collections.sort() 是一个非常常用的方法,用于对列表(List)中的元素进行排序。它位于 java.util.Collections 工具类中,支持对实现了 Comparable 接口的元素进行自然排序,也支持通过自定义 Comparator 实现灵活排序。

1. 对基本类型包装类排序

对于像 IntegerString 这样的内置类型,它们已经实现了 Comparable 接口,可以直接使用 Collections.sort() 进行升序排序。

示例:

List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);

Collections.sort(numbers);
System.out.println(numbers); // 输出: [1, 2, 5, 8]

字符串列表同理,会按字典顺序排序:

立即学习Java免费学习笔记(深入)”;

List<String> words = Arrays.asList("banana", "apple", "cherry");
Collections.sort(words);
System.out.println(words); // 输出: [apple, banana, cherry]

2. 对自定义对象排序(实现 Comparable)

如果你有一个自定义类,比如 Student,可以通过实现 Comparable<Student> 接口来定义默认排序规则(如按分数排序)。

class Student implements Comparable<Student> {
    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); // 按分数升序
    }
}

使用方式:

List<Student> students = new ArrayList<>();
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 作为参数。

序列猴子开放平台
序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台0
查看详情 序列猴子开放平台

例如,按学生姓名排序:

Collections.sort(students, new Comparator<Student>() {
    @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()); // 降序排列

基本上就这些。掌握自然排序和自定义比较器的使用,就能应对大多数排序场景了。

以上就是Java中Collections.sort排序列表使用的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号