在 Java 中对二维数组进行排序 [英] Sorting a 2d array in Java
本文介绍了在 Java 中对二维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难弄清楚对二维整数数组进行排序的一行代码的细节.
Im having a little of a hard time figuring out the specifics of a line of code that sorts a 2d array of integers.
正在排序的数组是一个数组,里面的数组只有两个数字,我想弄清楚 (a, b)
是否指的是两个单独的二维数组,如果 (a[0] , b[0])
指的是二维数组中的数字?
The array that is being sorted is an array that has arrays inside that only have two numbers, I am trying to figure out if (a, b)
refers to two separate 2d arrays and if (a[0] , b[0])
refers to the numbers within the 2d arrays?
Arrays.sort(sortedIntervals, (a, b) -> Integer.compare(a[0], b[0]));
推荐答案
您可以使用密钥提取器和比较器链:
int[][] arr2d = {{1, 3, 6}, {1, 2, 3}, {0, 2, 3}};
// sorting the rows of a 2d array first by
// the first column, then by the second column
Arrays.sort(arr2d, Comparator
.<int[]>comparingInt(row -> row[0])
.thenComparingInt(row -> row[1]));
System.out.println(Arrays.deepToString(arr2d));
// [[0, 2, 3], [1, 2, 3], [1, 3, 6]]
这篇关于在 Java 中对二维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文