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.
Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.
You can sort within the array using Arrays. sort() method, or if you want to sort in a different array, you can take following steps: Copy the array to new array. Sort the new array and then sort.
Collections.sort() works for objects Collections like ArrayList, LinkedList, etc. Using the reverse order method: This method will sort the array in the descending. In Java Collections class also provides the reverseOrder() method to sort the array in reverse-lexicographic order.
To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With