问题
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?
回答1:
Solution 1: sort the arrays by the second element, and then sort the arrays by the first element. Since Arrays.sort
is stable, that's equivalent to first comparing by the first element, then the second.
Solution 2: modify your comparator as follows:
Arrays.sort(hand, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
if (o1[0] == o2[0]) {
return Integer.compare(o1[1], o2[1]);
} else {
return Integer.compare(o1[0], o2[0]);
}
}
});
or, with Guava (disclosure: I contribute to Guava), you can just write the comparator as
public int compare(int[] o1, int[] o2) {
return ComparisonChain.start()
.compare(o1[0], o2[0])
.compare(o1[1], o2[1])
.result();
}
回答2:
Would this work for you:
int compare1 = Integer.valueOf(o1[1]).compareTo(Integer.valueOf(o2[1]);
if(compare1 != 0)
return compare1;
else
return Integer.valueOf(o1[0]).compareTo(Integer.valueOf(o2[0]));
回答3:
I will add a Java 8 solution, just in case someone wants to know.
Arrays.sort(hand, (o1, o2) -> o1[1] == o2[1] ? Integer.compare(o1[0], o2[0])
: Integer.compare(o1[1], o2[1]));
Basically, it compares the first element of each array when second element is equal, otherwise just compare the second elements directly.
来源:https://stackoverflow.com/questions/10321123/need-help-sorting-two-dimensional-arrays-by-second-element-and-then-by-first-ele