2
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. After I sort it based on the value point I want to sort it again based on the value goalScored. So, if the points of two teams are equal, I want to sort it again based on the goalScored value.

How can I do that?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Dawn17
  • 7,825
  • 16
  • 57
  • 118
  • Possible duplicate of [Using Comparable for multiple dynamic fields of VO in java](https://stackoverflow.com/questions/16206629/using-comparable-for-multiple-dynamic-fields-of-vo-in-java) – SedJ601 Dec 04 '17 at 14:35

3 Answers3

9

Java 8's enhancements to the Comparator interface give you a pretty elegant way of achieving this:

table.sort(Comparator.comparingInt(LeagueTableItem::getPoints)
                     .thenComparingInt(LeagueTableItem::goalScored));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

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;
}
sma
  • 9,449
  • 8
  • 51
  • 80
1
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. 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.

  • Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Dec 04 '17 at 15:03