我正在编写一个代码来验证我的对象的状态。我写的代码对对象的输入列表进行排序,然后进行范围检查。
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表达式编写此排序?
答案 0 :(得分:4)
您使用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()