gpt4 book ai didi

java - 如何按字典顺序对二维数组进行排序?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:37:44 27 4
gpt4 key购买 nike

假设我们有一个二维数组如下:

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.

如果您想修改 数组,那么使用Arrays.sort 就足够了:

Arrays.sort(source, Arrays::compare); 

鉴于您想要一个数组作为结果,那么我会采用流式方式:

int[][] sorted = Arrays.stream(source)
.sorted(Arrays::compare)
.toArray(int[][]::new);

关于java - 如何按字典顺序对二维数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53899289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com