簡體   English   中英

如何使用兩個不同的值對Java列表進行排序?

[英]How can I sort a Java list using two different values?

public void sortLeagueTable(List<LeagueTableItem> table) {
    Collections.sort(table, new Comparator<LeagueTableItem>(){
        public int compare(LeagueTableItem o1, LeagueTableItem o2){
            return o2.getPoints() - o1.getPoints();
        }
    });
}

此代碼根據名為points的對象的值對兩個列表進行排序。 在我根據值point進行排序后,我想根據值goalScored再次對其進行排序。 所以,如果兩支球隊的分數相等,我想根據goalScored值再次對其進行排序。

我怎樣才能做到這一點?

Java 8對Comparator界面的增強為您提供了一種非常優雅的方法來實現這一目標:

table.sort(Comparator.comparingInt(LeagueTableItem::getPoints)
                     .thenComparingInt(LeagueTableItem::goalScored));

只需在比較器中添加另一個條件:

public int compare(LeagueTableItem o1, LeagueTableItem o2){
     int diff = o2.getPoints() - o1.getPoints();
     if (diff == 0) {
        diff = o2.goalScored() - o1.goalScored();
     }
     return diff;
}
public int compare(LeagueTableItem o1, LeagueTableItem o2) {
        if (o2.getPoints() == o1.getPoints()) {

            return o2.goalsScored() - o1.goalsScored();
        } else {
            return o2.getPoints() - o1.getPoints();
        }
    }

首先,它獲得o1和o2的點並進行比較。 如果它們相等,則if語句繼續計算哪個o有更多的目標得分並返回結果,否則如果點不相等則返回結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM