一、基础排序实现
1.1 自然序排序(正序)
- List<Entity> sortedList = originalList.stream()
- .sorted(Comparator.comparing(Entity::getId))
- .collect(Collectors.toList());
复制代码
1.2 反向排序(倒序)
- List<Entity> sortedList = originalList.stream()
- .sorted(Comparator.comparing(Entity::getId).reversed())
- .collect(Collectors.toList());
复制代码
二、进阶排序技巧
2.1 空值安全处理
- // 处理可能为null的字段
- Comparator<Entity> nullSafeComparator = Comparator.comparing(
- Entity::getId,
- Comparator.nullsFirst(Comparator.naturalOrder())
- );
-
- List<Entity> sortedList = originalList.stream()
- .sorted(nullSafeComparator)
- .collect(Collectors.toList());
复制代码
2.2 多字段组合排序
- List<Entity> sortedList = originalList.stream()
- .sorted(Comparator.comparing(Entity::getDepartment)
- .thenComparing(Entity::getId))
- .collect(Collectors.toList());
复制代码
三、性能优化建议
3.1 并行流加速(适用于大数据量)
- List<Entity> sortedList = originalList.parallelStream()
- .sorted(Comparator.comparing(Entity::getId))
- .collect(Collectors.toList());
复制代码
3.2 原地排序(修改原集合)
- originalList.sort(Comparator.comparing(Entity::getId));
复制代码
四、最佳实践
- ArrayList<Entity> sortedList = originalList.stream()
- .sorted(Comparator.comparing(Entity::getId))
- .collect(Collectors.toCollection(ArrayList::new));
复制代码
- List<Entity> sortedList = new ArrayList<>(originalList);
- sortedList.sort(Comparator.comparing(Entity::getId));
复制代码
- List<Entity> sortedList = originalList.stream()
- .sorted((e1, e2) -> {
- // 自定义比较逻辑
- return e1.getId().compareTo(e2.getId());
- })
- .collect(Collectors.toList());
复制代码
五、注意事项
- 不可变性:返回的List实现可能不支持修改
- 空指针防护:推荐始终使用
- Comparator.nullsFirst/nullsLast
复制代码 - 性能权衡:超过10万条数据时优先考虑传统排序方式
- 对象状态: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省略
- }
复制代码
七、总结对比
排序方式 | 时间复杂度 | 空间复杂度 | 适用场景 |
---|
Stream顺序流 | O(n log n) | O(n) | 通用场景 | Stream并行流 | O(n log n) | O(n) | 大数据量(10w+) | Collections.sort | O(n log n) | O(1) | 原地修改需求 | 数据库排序 | O(n log n) | O(1) | 数据源在数据库时 |
通过合理选择排序策略,可以在保证代码简洁性的同时兼顾系统性能。建议根据实际业务场景选择最合适的排序方式。
到此这篇关于Java中Stream实现List排序的六个核心技巧的文章就介绍到这了,更多相关Java Stream实现List排序内容请搜索晓枫资讯以前的文章或继续浏览下面的相关文章希望大家以后多多支持晓枫资讯! 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |