I am sorting a 2D array by the value of one column. The first column holds the country code, the second column holds the names of the skaters for that country, the third column holds the score for that country:
skateArray[1][0] = "JPN";
skateArray[1][1] += "Yuzuru HANYU";
skateArray[1][2] = "13";
skateArray[2][0] = "USA";
skateArray[2][1] = "Jeremy ABBOTT "
skateArray[2][2] = "17";
I have it working like this:
Arrays.sort(skateArray, new Comparator<String[]>() {
public int compare(final String[] entry1, final String[] entry2)
{
final String firstScore = entry1[2];
final String secondScore = entry2[2];
return secondScore.compareTo(firstScore);
}
});
for (final String[] string : skateArray) {
System.out.println(string[0] + " " + string[1] + " " + string[2]);
}
Everything works except this one quirk in the output:
GBR 8.0
RUS 37.0
CAN 32.0
USA 27.0
JPN 24.0
ITA 23.0
CHN 20.0
FRA 20.0
GER 17.0
UKR 10.0
As you can see, the country with the lowest score (GBR, 8.0) is displayed first. The rest are displayed in descending order like I want. I can't figure out why.
It's because you are comparing the scores as strings, so they are sorted alphabetically.
Try replacing the last line of your function with this:
return new Double(secondScore).compareTo(new Double(score1));
You're parsing each score entry as a string. In that sense, 8
(the character) always comes after 1
(the character), so the result should not be surprising.
I would strongly recommend parsing the score as a float or integer and comparing them that way. Then you should get the results you want.
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