如何按字典顺序对二维数组进行排序?
How to sort two dimensional array lexicographically?
假设我们有一个二维数组如下:
int[][] source = {
{ 3, 5, 6, 1},
{ 3, 3, 5, -6},
{ -1, -3, -5, -6},
{ 124, 43, 55, -66}
};
我们如何对多维数组进行排序source
字典顺序?
因此,我希望它是:
[ [ -1, -3, -5, -6],
[ 3, 3, 5, -6],
[ 3, 5, 6, 1],
[124, 43, 55, -66] ]
这个网站上的很多问题似乎只建议按每个数组的第一个元素或第二个、第三个等排序,而不是考虑整个数组。
从 JDK9 开始,有一个名为 Arrays.compare
的新方法,它允许您按字典顺序 比较两个给定数组 。
文档中 Arrays.compare
的简短描述:
If the two arrays share a common prefix then the lexicographic
comparison is the result of comparing two elements, as if by
Integer.compare(int, int), at an index within the respective arrays
that is the prefix length. Otherwise, one array is a proper prefix of
the other and, lexicographic comparison is the result of comparing the
two array lengths.
如果您想 修改 source
数组,那么使用 Arrays.sort
就足够了:
Arrays.sort(source, Arrays::compare);
鉴于您想要一个 new 数组作为结果,那么我会采用流式处理方式:
int[][] sorted = Arrays.stream(source)
.sorted(Arrays::compare)
.toArray(int[][]::new);
假设我们有一个二维数组如下:
int[][] source = {
{ 3, 5, 6, 1},
{ 3, 3, 5, -6},
{ -1, -3, -5, -6},
{ 124, 43, 55, -66}
};
我们如何对多维数组进行排序source
字典顺序?
因此,我希望它是:
[ [ -1, -3, -5, -6],
[ 3, 3, 5, -6],
[ 3, 5, 6, 1],
[124, 43, 55, -66] ]
这个网站上的很多问题似乎只建议按每个数组的第一个元素或第二个、第三个等排序,而不是考虑整个数组。
从 JDK9 开始,有一个名为 Arrays.compare
的新方法,它允许您按字典顺序 比较两个给定数组 。
文档中 Arrays.compare
的简短描述:
If the two arrays share a common prefix then the lexicographic comparison is the result of comparing two elements, as if by Integer.compare(int, int), at an index within the respective arrays that is the prefix length. Otherwise, one array is a proper prefix of the other and, lexicographic comparison is the result of comparing the two array lengths.
如果您想 修改 source
数组,那么使用 Arrays.sort
就足够了:
Arrays.sort(source, Arrays::compare);
鉴于您想要一个 new 数组作为结果,那么我会采用流式处理方式:
int[][] sorted = Arrays.stream(source)
.sorted(Arrays::compare)
.toArray(int[][]::new);