I have a two dimensional array that is holding the value of 5 cards. The first element of each of the 5 arrays represents the suit of the card, and the second element represents the card value.
I want to sort the 2d array by the second element, and then by the first element while maintaining the sorted order of the second element (if that makes sense). For example all suits of ones will be lower on the sorted list than all suits of two. So for example, {{0,1},{2,1},{0,2}} should become {{0,1},{2,1},{0,2}}.
Here is what I have:
// {{3,2}, {2,2}, {0,1}, {1,0}, {2,3}} should become
// {{1,0}, {0,1}, {2,2}, {3,2}, {2,3}}
int[][] hand = {{3,2},{2,2},{0,1},{1,0},{2,3}};
sort(hand);
public static void sort(int[][] hand){
Arrays.sort(hand, new Comparator<int[]>(){
public int compare(int[] o1, int[] o2){
return Integer.valueOf(o1[1]).compareTo(Integer.valueOf(o2[1]));
}
});
}
This is outputting {{1,0},{0,1},{3,2},{2,2},{2,3}}. Does anyone have any suggestions?
Solution 1: sort the arrays by the second element, and then sort the arrays by the first element. Since
Arrays.sortis stable, that’s equivalent to first comparing by the first element, then the second.Solution 2: modify your comparator as follows:
or, with Guava (disclosure: I contribute to Guava), you can just write the comparator as