我正在编写代码以验证对象的状态。我编写的代码对对象的输入列表进行排序,然后进行范围检查。
private boolean validateStates(List<ConcessionState> concessionStateList) {
long startRange,endRange = 0;
Collections.sort(concessionStateList , new Comparator<ConcessionState>() {
@Override
public int compare(ConcessionState o1, ConcessionState o2) {
return (int)(long)(o1.getRangeStart() - o2.getRangeStart());
}
........
}
有没有办法使用Lambda表达式编写这种排序?
最佳答案
您使用Comparator.comparing(Function<? super T,? extends U> keyExtractor)
。
如下:
private boolean validateStates(List<ConcessionState> concessionStateList) {
long startRange,endRange = 0;
Collections.sort(concessionStateList,
Comparator.comparing(ConcessionState::getRangeStart));
.......
}
如果要按降序排列,可以
Comparator.comparing(ConcessionState::getRangeStart)
.reversed()