加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 08:28:26 所属栏目:Java 来源:网络整理
导读:假设我们有一个二维数组如下: int[][] source = { { 3,5,6,1},{ 3,3,-6},{ -1,-3,-5,{ 124,43,55,-66}}; 我们如何按字典顺序对多维数组源进行排序? 所以,结果,我希望它是: [ [ -1,-6],[ 3,1],[124,-66] ] 这个网站上的很多问题似乎只建议按每个数组的第一
假设我们有一个二维数组如下:

int[][] source = {
  {   3,5,6,1},{   3,3,-6},{  -1,-3,-5,{ 124,43,55,-66}
};

我们如何按字典顺序对多维数组源进行排序?

所以,结果,我希望它是:

[ [ -1,-6],[  3,1],[124,-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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读