📌 参数顺序与排序方向的关系
Lambda表达式 (a, b) -> { ... } 中,a 和 b 是待比较的两个对象。返回值决定了它们的相对顺序:
- 正数:
a排在b之后 - 负数:
a排在b之前 - 零:两者相等
升序 vs 降序规律
| 排序方向 | Lambda表达式写法 | 解释 |
|---|---|---|
| 升序 | a.compareTo(b) 或 a - b | a 本应在前时返回负值,触发升序 |
| 降序 | b.compareTo(a) 或 b - a | b 在前时返回负值,触发降序 |
🎓 学生成绩排序场景
需求:先按成绩降序排列,成绩相同则按学号升序排列。
1. 定义学生类
public class Student {
private int id; // 学号
private int score; // 成绩
// 构造方法、Getter、toString等
}
2. 实现排序的两种方式
方式一:Lambda表达式直接实现
List<Student> students = ...; // 初始化学生列表
students.sort((a, b) -> {
// 1. 按成绩降序
int scoreCompare = Integer.compare(b.getScore(), a.getScore());
if (scoreCompare != 0) {
return scoreCompare;
}
// 2. 成绩相同,按学号升序
return Integer.compare(a.getId(), b.getId());
});
方式二:组合Comparator方法
更简洁的链式调用:
import java.util.Comparator;
students.sort(
Comparator.comparingInt(Student::getScore)
.reversed() // 成绩降序
.thenComparingInt(Student::getId) // 学号升序
);
3. 验证排序结果
// 测试数据
List<Student> students = Arrays.asList(
new Student(101, 85),
new Student(102, 90),
new Student(103, 85)
);
// 排序后输出
students.forEach(System.out::println);
输出结果:
Student{id=102, score=90} // 成绩最高
Student{id=101, score=85} // 成绩相同,学号小在前
Student{id=103, score=85}
📝 关键总结
- 参数顺序决定方向:
a - b是升序,b - a是降序。 - 多条件排序:优先处理主要条件,再通过
if-return或thenComparing处理次要条件。 - 避免直接相减:使用
Integer.compare(a, b)而非a - b,避免整数溢出问题。