我正在尝试对以下数组进行排序:
int hitlist[][] = new int [17][2];
排序信息总是在 hitlist[i][0]
中,而且是数字,但我找不到 Arrays.sort
的正确方法。
输入看起来像:
[0, 0]
[4, 0]
[3, 1]
[4, 2]
[4, 4]
[5, 6]
[4, 7]
[4, 8]
[1, 9]
[4, 11]
[4, 12]
[2, 13]
[4, 14]
[4, 15]
[0, 0]
[0, 0]
[0, 0]
现在我希望它像这样排序:
[1, 9]
[2, 13]
[3, 1]
[4, 0]
[4, 2]
[4, 4]
[4, 7]
[4, 8]
[4, 11]
[4, 12]
[4, 14]
[4, 15]
最佳答案
如果你想根据索引对数组进行排序,你可以使用 Arrays::sort
与 Comparator::comparingInt
int index = 0;
Arrays.sort(hitlist, Comparator.comparingInt(arr -> arr[index]));
这是 Ideone 中的示例
编辑
基于您的 comment和 comment ,你想在排序后忽略数组中的 [0, 0]
,在这种情况下你可以使用:
int[][] hitlist = {{0, 0}, {4, 0}, {3, 1}, {4, 2}, {4, 4}, {5, 6}, {4, 7}, {4, 8}, {1, 9}, {4, 11}, {4, 12}, {2, 13}, {4, 14}, {4, 15}, {0, 0}, {0, 0}, {0, 0}};
int index = 0;
int[][] sortedArray = Arrays.stream(hitlist)
.filter(arr -> arr[0] != 0 && arr[1] != 0)
.sorted(Comparator.comparingInt(arr -> arr[index]))
.toArray(int[][]::new);
输出
[1, 9]
[2, 13]
[3, 1]
[4, 2]
[4, 4]
[4, 7]
[4, 8]
[4, 11]
[4, 12]
[4, 14]
[4, 15]
[5, 6]
关于java - 如何在java中对特定的二维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54833360/