JavaList对象排序技巧详解
时间:2026-04-26
浏览:483
作者:佚名
本文深入解析了Java中对List集合按对象属性排序的多种高效方法,重点介绍了Java 8引入的Comparator.comparing()、thenComparing()和reversed()等函数式API,支持单属性升/降序、多级联排序,并对比了原地排序与Stream流式排序(生成新列表)两种策略,兼顾代码简洁性、可读性与不可变性需求,是Java开发者提升集合操作能力的实用指南。

在Java中,可以根据对象的属性对List进行排序,常用的方式是使用Collections.sort()或List自带的sort()7a8b6c3e>方法结合Comparator。从Java 8开始,推荐使用Stream API或Comparator的便捷方法来实现,代码更简洁清晰。
1. 使用 Comparator.comparing()(Java 8+)
假设有一个Person类,包含name和age属性:
class Person {
private String name;
private int age;
// 构造函数
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter方法
public String getName() { return name; }
public int getAge() { return age; }
@Override
public String toString() {
return name + "(" + age + ")";
}
}
要根据age对List<Person>排序:
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// 按年龄升序排序
people.sort(Comparator.comparing(Person::getAge));
System.out.println(people);
// 输出: [Bob(25), Alice(30), Charlie(35)]
2. 按多个属性排序
如果需要先按age排序,再按name排序:
people.sort(Comparator.comparing(Person::getAge)
.thenComparing(Person::getName));
这样会先按年龄升序,年龄相同时按姓名字母顺序排列。
3. 降序排序
使用reversed()方法实现降序:
// 按年龄降序 people.sort(Comparator.comparing(Person::getAge).reversed());
4. 使用 Stream 排序(不修改原列表)
如果不想改变原List,可以使用Stream生成新列表:
List<Person> sorted = people.stream()
.sorted(Comparator.comparing(Person::getName))
.collect(Collectors.toList());
这种方式适合需要保留原始顺序的场景。
基本上就这些常见用法。使用Comparator配合方法引用,代码简洁且可读性强。终于介绍完啦!小伙伴们,这篇关于《JavaList对象排序技巧详解》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
