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

目录

1、list.sort()

2、Collections.sort()

3、Stream.sorted()

4、进阶排序技巧

[4.1 空值安全处理](#4.1 空值安全处理)

[4.2 多字段组合排序](#4.2 多字段组合排序)

[4.3. 逆序](#4.3. 逆序)

5、性能优化建议

[5.1 并行流加速](#5.1 并行流加速)

[5.2 原地排序](#5.2 原地排序)

6、最佳实践

7、注意事项


前言

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

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


1、list.sort()

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

java 复制代码
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 之前的版本,或者习惯使用传统的排序方式。

java 复制代码
Collections.sort(list, Comparator.comparing(Entity::getId));

3、Stream.sorted()

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

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

1.自然序排序(正序)

java 复制代码
    @Test
    public 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()));
    }
java 复制代码
输出示例:
李四::1
王武::2
张三::3

2.反向排序(倒序)

java 复制代码
    @Test
    public 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()));
    }
java 复制代码
输出示例:
张三::3
王武::2
李四::1

4、进阶排序技巧

4.1 空值安全处理

java 复制代码
// 处理可能为null的字段
Comparator<Person> nullSafeComparator = Comparator.comparing(
    Person::getId, 
    Comparator.nullsFirst(Comparator.naturalOrder())
);

List<Person> sortedList = originalList.stream()
        .sorted(nullSafeComparator)
        .collect(Collectors.toList());

4.2 多字段组合排序

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

4.3. 逆序

java 复制代码
list.sort(Comparator.comparingInt(Entity::getId).reversed());

5、性能优化建议

5.1 并行流加速

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

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

5.2 原地排序

使用范围:修改原集合

java 复制代码
originalList.sort(Comparator.comparing(Person::getId));

6、最佳实践

1.类型明确化:

推荐指定具体集合类型

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

2.防御性拷贝:

保持原集合不可变

java 复制代码
List<Entity> sortedList = new ArrayList<>(originalList);
sortedList.sort(Comparator.comparing(Entity::getId));

3.Lambda优化:

复杂场景使用Lambda表达式

java 复制代码
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操作不会修改原始集合元素

举例:

java 复制代码
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博客

相关推荐
Bruce_Liuxiaowei10 分钟前
元组与具名元组:把「第 3 个字段」变成「price」
数据结构·python·语法·元组
今晚打老虎11 小时前
c++之提高A(前缀和)(第三课)
数据结构·c++·算法
不会就选b12 小时前
算法日常・每日刷题--<贪心>26
数据结构·算法
Logic10116 小时前
C语言/数据结构位运算题解:异或XOR找出书柜中编号只出现一次的那一层——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
青山木16 小时前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
SelectDB技术团队18 小时前
Apache Doris 高性能 Open Lake Variant 读写技术解析(含对比数据)
数据结构·数据库·clickhouse·日志·apache doris·selectdb·湖仓架构升级
kiracrimson18 小时前
希尔排序:让插入排序不再怕逆序
数据结构·算法·排序算法
Logic10118 小时前
C语言/数据结构位运算题解:异或XOR找出星球探险中的“独特能量石“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
hnjzsyjyj21 小时前
洛谷 P1339:[USACO09OCT] Heat Wave G ← Bellman-Ford 算法
数据结构·bellman-ford 算法
SelectDB技术团队1 天前
ClickHouse 存日志的能力边界:并发、检索与 trace 回放的实测对照
数据结构·数据库·clickhouse·日志分析·apache doris·日志存储