使用Lambda表达式对birthYear降序排序失败,请求代码排查协助
没问题,我来帮你排查Lambda表达式对birthYear降序排序的问题~
排查Lambda实现birthYear降序排序的常见问题
首先你用Arrays.asList生成的students列表是支持排序操作的,问题大概率出在排序逻辑的Lambda写法上,我整理了几种常见错误和对应的正确写法:
错误1:仅使用默认升序比较,未添加降序处理
如果你的排序代码是这样的:
students.sort(Comparator.comparingInt(Student::getBirthYear));
这会默认按升序排列birthYear(从1989到2000),要实现降序,只需在比较器后调用reversed()方法:
students.sort(Comparator.comparingInt(Student::getBirthYear).reversed());
错误2:手动写Lambda时逻辑搞反
有的同学会尝试自己写比较逻辑,但容易搞反升序降序的计算方式,比如:
// 错误示例:a.getBirthYear() - b.getBirthYear()是升序逻辑 students.sort((a, b) -> a.getBirthYear() - b.getBirthYear());
正确的Lambda降序写法应该是用后者减前者:
students.sort((a, b) -> b.getBirthYear() - a.getBirthYear());
额外提醒:不想修改原列表的话要先复制
Arrays.asList返回的是基于原数组的视图,排序会直接修改原列表。如果需要保留原数据,建议先创建新列表再排序:
List<Student> sortedStudents = new ArrayList<>(students); sortedStudents.sort(Comparator.comparingInt(Student::getBirthYear).reversed());
你可以对照上面的情况检查自己的代码,如果还是有问题,把你的排序代码贴出来,我再帮你进一步分析!
内容的提问来源于stack exchange,提问作者Storg
相关产品推荐
相关产品推荐

