(Java) How can I sort an array of objects, and break ties between two objects?

arrays, java, object, sorting

Solution

Similar to Ben's answer, but a bit different, I often use the following pattern for clarity. This is a Comparator, but the code for Comparable would be similar.

Comparator<Team> myComparator = new Comparator() {
   @Override
   public int compare(Team t1, Team t2) {
      int result = t1.getWins() - t2.getWins();
      if (result == 0)
         result = t2.getLosses() - t1.getLosses();
      if (result == 0)
         ... more tests here

      return result;
   }

};

Note that taking the difference of two integers might overflow in extreme cases, so a more robust variation would use `Integer.compare(t1.getWins(), t2.getWins())`. However, in this case, it is unlikely that your teams will have more than 2^31 wins or losses. :-)

To use this, go

Arrays.sort(myArrayOfTeams, myComparator);

Problem

Say I have an object - `Team`. `Team` has three fields, `wins`, `losses` and `draws`. If I have a few objects say `Team1`, `Team2`, `Team3`, where `Team1` has 3 wins, 2 losses, and 1 tie, `Team2` has 3 wins and 3 losses, and `Team3` has 2 wins, 3 losses, and 1 tie. Put all three teams in an array. I am trying to sort (I know how to do this.. implement `Comparable`, override `compareTo()` use `Array.sort`) them by wins, and if two teams have the same wins, I want to then sort them by losses (and eventually a third field will be added to further break ties). Should I write my own sort method? Can someone point me in the right direction because I have no clue where to go with this.

Original source