英文:
How to sort two dimensional array using Comparator in java
问题
int[][] arr = {{1, 2, 3}, {}, {3}, {1, 4}, {3, 2}, {3, 3, 5}};
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[0] == o2[0])
return o1[1] - o2[1];
return o2[0] - o1[0];
}
});
for (int[] ints : arr) {
for (int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
英文:
I need to sort such an array by descending the elements of the first column. In the case of equality of elements in the first column, the elements of the second column must be sorted in ascending order. But this what I need else is to check and put empty row to the end of matrix, and row with only one element put prior to the same which has more elements.
For example in this array {3}
- it is the first row, {}
- the last one.
int[][] arr = {{1, 2, 3}, {}, {3}, {1, 4}, {3, 2}, {3, 3, 5}};
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[0] == o2[0])
return o1[1] - o2[1];
return o2[0] - o1[0];
}
});
for (int[] ints : arr) {
for (int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
答案1
得分: 4
以下Comparator<int[]>
可用于排序:
-
将空数组放在最后。
-
按升序排列相同索引处的较大数字。
-
如果较小的数组在索引0处首先出现在较大的数组之前(按长度来衡量),则将较小的数组视为比较靠前。
以下是一个根据您的需要轻松修改的算法:
int[][] arr = {{1, 2, 3}, {}, {3}, {1, 4}, {3, 2, 2}, {3, 3, 5}, {3, 2}};
Arrays.sort(arr, (o1, o2) -> {
if (o1.length == 0) { return 1; } // 空数组排在最后
if (o2.length == 0) { return -1; } // 空数组排在最后
int min = Math.min(o1.length, o2.length); // 避免ArrayIndexOutOfBoundsException的上限
for (int i = 0; i < min ; i++) {
if (o1[i] != o2[i]) { // 比较索引上的值
return o1[i] - o2[i]; // 如果不同,则返回差值
}
}
return 1; // o1靠前,因此它排在前面
});
System.out.println(Arrays.deepToString(arr));
输出将是:
[[1, 2, 3], [1, 4], [3], [3, 2, 2], [3, 2], [3, 3, 5], []]
英文:
The following Comparator<int[]>
enables sorting by:
-
Empty arrays as last
-
Bigger number at the same index in the ascending order
-
In case the smaller array first into larger (in terms of length) starting at index 0, which one comes first is considered smaller compared to the latter one.
Here is an algorithm can be easily modified according to your needs:
int[][] arr = {{1, 2, 3}, {}, {3}, {1, 4}, {3, 2, 2}, {3, 3, 5}, {3, 2}};
Arrays.sort(arr, (o1, o2) -> {
if (o1.length == 0) { return 1; } // empty last
if (o2.length == 0) { return -1; } // empty last
int min = Math.min(o1.length, o2.length); // upper bound to avoid ArrayIndexOutOfBoundsException
for (int i = 0; i < min ; i++) {
if (o1[i] != o2[i]) { // compare values on indices
return o1[i] - o2[i]; // return if different
}
}
return 1; // it goes first so it lefts first
}
);
System.out.println(Arrays.deepToString(arr));
The output will be:
> [[1, 2, 3], [1, 4], [3], [3, 2, 2], [3, 2], [3, 3, 5], []]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论