viv*_*ox3 2 java arrays sorting
我有一个名为 interval[g][2] 的二维数组,其中 g 是某个数字。目前,我试图通过增加第一个元素中的顺序对数组进行排序,如果它们相等,则按第二个元素中的降序排序。
我以两种方式尝试过:
1) 使用 Java 8 的 Comparator.comparing 方法:
Arrays.sort(interval, Comparator.comparing((int[] arr) -> arr[0]));
Run Code Online (Sandbox Code Playgroud)
2) 使用 Arrays.sort:
Arrays.sort(interval, new Comparator<int[]>() {
@Override
public int compare(int[] s1, int[] s2) {
if (s1[0] > s2[0])
return 1;
else if (s1[0] < s2[0])
return -1;
else {
if(s1[1] < s2[1])
return 1;
else if (s1[1] > s2[1])
return -1;
else
return 0;
}
}
});
Run Code Online (Sandbox Code Playgroud)
第一个方法返回一个部分排序的列表。
[[0, 10], [10, 30], [30, 50]]
[[0, 10], [3, 19], [35, 45]]
[[10, 30], [27, 33], [30, 50]]
[[-10, 10], [0, 20], [35, 45]]
[[10, 30], [20, 40], [30, 50]]
[[0, 20], [8, 28], [37, 43]]
[[0, 20], [15, 35], [37, 43]]
[[0, 0], [8, 28], [10, 40]]
Run Code Online (Sandbox Code Playgroud)
如您所见,它在一组三个元组中对事物进行排序。
第二种方法根本不对数组进行排序。我不能使用原始数据类型进行排序吗?任何人都可以建议吗?
我想你正在寻找这个:
Arrays.sort(interval, Comparator.comparingInt((int[] arr) -> arr[0]).thenComparing(Comparator.comparingInt((int[] arr) -> arr[1]).reversed()));
Run Code Online (Sandbox Code Playgroud)
或者,如果您想使用 custom Comparator:
Arrays.sort(interval, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
int result = Integer.compare(o1[0], o2[0]);
if (result == 0) {
result = Integer.compare(o2[1], o1[1]);
}
return result;
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2713 次 |
| 最近记录: |