2014-09-29 61 views
1

我在寫代碼來驗證我的對象的狀態。我寫的代碼對輸入的對象列表進行排序,然後進行範圍檢查。如何使用Lambda表達式對其某個字段上的類對象列表進行排序?

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

這正是我需要的,謝謝! @aioobe – phoenix 2014-09-29 11:19:20

回答

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() 
相關問題