当前位置: 首页 > ai >正文

关于list集合排序的常见方法

目录

1、list.sort()

2、Collections.sort()

3、Stream.sorted()

4、进阶排序技巧

4.1 空值安全处理

4.2 多字段组合排序

4.3. 逆序

5、性能优化建议

5.1 并行流加速

5.2 原地排序

6、最佳实践

7、注意事项


前言

        Java中对于集合的排序操作,分别为list.sort()方法Collections.sort()方法,和Stream流实现List排序的核心技巧。

更多集合和数组的可参考:深入探讨集合与数组转换方法-CSDN博客


1、list.sort()

(Comparator) 方法(推荐)这是 Java 8 引入的最推荐的排序方式,语法简洁、可读性强。

List<Entity> list = new ArrayList<>();
list.add(new Entity(3));
list.add(new Entity(1));
list.add(new Entity(2));list.sort(Comparator.comparing(Entity::getId));

2、Collections.sort()

(list,Comparator)适用于 Java 8 之前的版本,或者习惯使用传统的排序方式。

Collections.sort(list, Comparator.comparing(Entity::getId));

3、Stream.sorted()

(惰性排序):适用于需要链式处理或中间处理的场景,但不会修改原始列表。

List<Entity> sortedList = list.stream().sorted(Comparator.comparing(Entity::getId)).collect(Collectors.toList());

1.自然序排序(正序)

    @Testpublic void test1() {List<Person> originalList = new ArrayList<>();originalList.add(new Person(3,"张三"));originalList.add(new Person(1,"李四"));originalList.add(new Person(2,"王武"));List<Person> sortedList = originalList.stream().sorted(Comparator.comparing(Person::getId)).collect(Collectors.toList());sortedList.forEach(person -> System.out.println(person.getId()));}
输出示例:
李四::1
王武::2
张三::3

2.反向排序(倒序)

    @Testpublic void test1() {List<Person> originalList = new ArrayList<>();originalList.add(new Person(3,"张三"));originalList.add(new Person(1,"李四"));originalList.add(new Person(2,"王武"));List<Person> sortedList = originalList.stream().sorted(Comparator.comparing(Person::getId).reversed()).collect(Collectors.toList());sortedList.forEach(person -> System.out.println(person.getName()+"::"+person.getId()));}
输出示例:
张三::3
王武::2
李四::1

4、进阶排序技巧

4.1 空值安全处理

// 处理可能为null的字段
Comparator<Person> nullSafeComparator = Comparator.comparing(Person::getId, Comparator.nullsFirst(Comparator.naturalOrder())
);List<Person> sortedList = originalList.stream().sorted(nullSafeComparator).collect(Collectors.toList());

4.2 多字段组合排序

List<Person> sortedList = originalList.stream().sorted(Comparator.comparing(Person::getName).thenComparing(Person::getId)).collect(Collectors.toList());

4.3. 逆序

list.sort(Comparator.comparingInt(Entity::getId).reversed());


5、性能优化建议

5.1 并行流加速

使用范围:适用于大数据量

List<Entity> sortedList = originalList.parallelStream().sorted(Comparator.comparing(Person::getId)).collect(Collectors.toList());

5.2 原地排序

使用范围:修改原集合

originalList.sort(Comparator.comparing(Person::getId));

6、最佳实践

1.类型明确化

推荐指定具体集合类型

ArrayList<Entity> sortedList = originalList.stream().sorted(Comparator.comparing(Person::getId)).collect(Collectors.toCollection(ArrayList::new));

2.防御性拷贝

保持原集合不可变

List<Entity> sortedList = new ArrayList<>(originalList);
sortedList.sort(Comparator.comparing(Entity::getId));

3.Lambda优化

复杂场景使用Lambda表达式

List<Entity> sortedList = originalList.stream().sorted((e1, e2) -> {// 自定义比较逻辑return e1.getId().compareTo(e2.getId());}).collect(Collectors.toList());

7、注意事项

  1. 不可变性Collectors.toList()返回的List实现可能不支持修改
  2. 空指针防护:推荐始终使用Comparator.nullsFirst/nullsLast
  3. 性能权衡:超过10万条数据时优先考虑传统排序方式
  4. 对象状态:Stream操作不会修改原始集合元素

举例:

public class SortingDemo {public static void main(String[] args) {List<Entity> entities = Arrays.asList(new Entity(2, "B"),new Entity(1, "A"),new Entity(3, "C"));// 多条件排序:先按名称倒序,再按ID正序List<Entity> sorted = entities.stream().sorted(Comparator.comparing(Entity::getName).reversed().thenComparing(Entity::getId)).collect(Collectors.toList());sorted.forEach(System.out::println);}
}class Entity {private int id;private String name;// 构造方法和getter省略
}


总结对比

        在 Java 中,对 List 集合进行排序是开发中非常常见的操作。

        Java 提供了多种方式来实现排序功能,每种方法都有其适用场景和特点。可以灵活地对 Java 中的 List 进行排序操作,根据具体需求选择最适合的方式。


参考文章:

1、Java Stream实现List排序的6个核心技巧_java list stream 排序-CSDN博客

http://www.xdnf.cn/news/10793.html

相关文章:

  • 《TCP/IP 详解 卷1:协议》第5章:Internet协议
  • 红黑树与红黑树的插入——用C++实现
  • Python----循环神经网络(BiLSTM:双向长短时记忆网络)
  • Rust 学习笔记:使用 cargo install 安装二进制 crate
  • 【氮化镓】GaN HMETs器件物理失效分析进展
  • NVIDIA CUDA Toolkit安装
  • 遥感影像建筑物变化检测
  • 前端与后端
  • [Java 基础]Java 是什么
  • 帝可得 - 设备管理
  • 谷歌地图高清卫星地图2026中文版下载|谷歌地图3D卫星高清版 V7.3.6.9796 最新免费版下载 - 前端工具导航
  • 阿里云为何,一个邮箱绑定了两个账号
  • Go语言学习-->第一个go程序--hello world!
  • xTimerChangePeriod无需先Stop
  • Ros(launch一键打开?)
  • 永磁同步电机无速度算法--互补滑模观测器
  • Unity-UI组件详解
  • 嵌入式复习小练
  • 【前端后端环境】
  • c++之STL容器的学习(上)
  • 用户退出了Token还能用?用Nest+Redis给JWT令牌加黑名单!
  • apisix + argorollout 实现蓝绿发布II-线上热切与蓝绿发布控制
  • 燃尽图和甘特图
  • 涨薪技术|0到1学会性能测试第93课-生产系统性能测试
  • LIMIT 和 OFFSET 在大数据量下的性能问题分析与优化方案
  • 动态规划-1143.最长公共子序列-力扣(LeetCode)
  • 【QT】自定义QWidget标题栏,可拖拽(拖拽时窗体变为normal大小),可最小/大化、关闭(图文详情)
  • Visual Studio Code
  • 自适应移动平均(Adaptive Moving Average, AMA)
  • Unity UI 性能优化--Sprite 篇