[英]Need help sorting two dimensional arrays by second element and then by first element (Java)
I have a two dimensional array that is holding the value of 5 cards.我有一个二维数组,其中包含 5 张卡的值。 The first element of each of the 5 arrays represents the suit of the card, and the second element represents the card value.
5 个数组中每个数组的第一个元素表示卡的花色,第二个元素表示卡的值。
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}}.
例如,{{0,1},{2,1},{0,2}} 应该变成 {{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}}.这是输出 {{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.解决方案1:按第二个元素对数组进行排序,然后按第一个元素对数组进行排序。 Since
Arrays.sort
is stable, that's equivalent to first comparing by the first element, then the second.由于
Arrays.sort
是稳定的,这相当于首先比较第一个元素,然后是第二个。
Solution 2: modify your comparator as follows:解决方案 2:按如下方式修改您的比较器:
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或者,使用 Guava(披露:我为 Guava 做出贡献),您可以将比较器写为
public int compare(int[] o1, int[] o2) {
return ComparisonChain.start()
.compare(o1[0], o2[0])
.compare(o1[1], o2[1])
.result();
}
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]));
I will add a Java 8 solution, just in case someone wants to know.我将添加一个 Java 8 解决方案,以防万一有人想知道。
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.基本上,当第二个元素相等时,它比较每个数组的第一个元素,否则直接比较第二个元素。
您可以像这样以更紧凑的方式使用 Java 8 Comparator
Arrays.sort(hand, Comparator.comparing(x -> ((int[])x)[1]).thenComparing(x -> ((int[])x)[0]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.