实现说明
活动部件是类 Employee、Main和函数 main。
使用要点
- 直接运行文件,输出会带上标签,比如
team=、level=——输出的每一行都能指回产生它的那次调用。
常见问题
运行「nullsFirst 处理空排序键」会打印什么?
整个文件跑完,输出行以 team=、level= 这类前缀开头。
核心语句
staff.sort(byLevel);
staff.sort(byTeam);
代码示例
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
record Employee(String name, String team, Integer level) {}
public class Main {
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>(List.of(
new Employee("ada", "core", 5),
new Employee("bob", null, 3),
new Employee("cy", "core", null),
new Employee("dee", "web", 4)
));
// nullsLast:为 null 的键排在最后,比较器内部不再抛 NPE
Comparator<Employee> byTeam = Comparator.comparing(
Employee::team, Comparator.nullsLast(Comparator.<String>naturalOrder()));
staff.sort(byTeam);
staff.forEach(e -> System.out.println("team=" + e.team() + " name=" + e.name()));
// nullsFirst + reverseOrder:null 在前,其余等级从高到低
Comparator<Employee> byLevel = Comparator.comparing(
Employee::level, Comparator.nullsFirst(Comparator.<Integer>reverseOrder()));
staff.sort(byLevel);
staff.forEach(e -> System.out.println("level=" + e.level() + " name=" + e.name()));
}
}