直接用Collections.max()配合Comparator.comparingDouble(Student::getScore)可一行获取最高分Student对象;需处理空集合异常,推荐流式写法orElse(null)更安全。

直接用 Collections.max() 配合自定义 Comparator,就能从 POJO 列表中一行代码拿到最高分对象——关键在于让比较器明确“按哪个字段比、怎么比”。
确保 POJO 有可访问的分数字段
比如有个学生类 Student,含 score(double 或 int 类型):
private String name;
private double score;
// 构造、getter 省略
}
用 Lambda 写简洁的 Comparator
不用单独写类,用 Lambda 表达式最直观:
Collections.max(students, Comparator.comparingDouble(Student::getScore))- 如果
score是int,用comparingInt更高效 - 若要降序取“最高分”,默认就是升序比较后取最大,所以无需额外翻转;但若字段可能为
null,需加thenComparing或用Comparator.nullsLast
处理空列表或 null 值的健壮写法
Collections.max() 遇到空集合会抛 NoSuchElementException:
- 提前判空:
if (students == null || students.isEmpty()) { /* 返回默认值或抛业务异常 */ } - 或改用 Java 8+ 的流式写法更安全:
students.stream().max(Comparator.comparingDouble(Student::getScore)).orElse(null)
扩展:多个条件排序时取最高分(同分看年龄小者)
用链式比较器,优先级从左到右:
Collections.max(students,Comparator.comparingDouble(Student::getScore)
.thenComparingInt(Student::getAge));

















