简体   繁体   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();
        }
    });
}

This code sorts two lists based on the value of the object called points. 此代码根据名为points的对象的值对两个列表进行排序。 After I sort it based on the value point I want to sort it again based on the value goalScored . 在我根据值point进行排序后,我想根据值goalScored再次对其进行排序。 So, if the points of two teams are equal, I want to sort it again based on the goalScored value. 所以,如果两支球队的分数相等,我想根据goalScored值再次对其进行排序。

How can I do that? 我怎样才能做到这一点?

Java 8's enhancements to the Comparator interface give you a pretty elegant way of achieving this: Java 8对Comparator界面的增强为您提供了一种非常优雅的方法来实现这一目标:

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

Just add another condition to your comparator: 只需在比较器中添加另一个条件:

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();
        }
    }

First it gets the o1 and o2's points and compare them. 首先,它获得o1和o2的点并进行比较。 If they are equal, the if statement proceed to calculate which o has more goals scored and returns the result, else if the points are NOT equal it returns the result. 如果它们相等,则if语句继续计算哪个o有更多的目标得分并返回结果,否则如果点不相等则返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM