按第一列对2d数组进行排序,然后对第二列进行排序 [英] Sort a 2d array by the first column and then by the second one

查看:56
本文介绍了按第一列对2d数组进行排序,然后对第二列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int[][] arrs = {{1, 100}, {11, 22}, {1, 11}, {2, 12}};
Arrays.sort(arrs, (a, b) -> (a[0] - b[0]));

上面的数组已排序为

{1, 100}
{1, 11}
{2, 12}
{11, 22}

我希望它们首先按 a [0] -b [0] 排序,如果 a [0] = b [0] ,则按 a [1] -b [1] .

I want them to be sorted by a[0]-b[0] first and if a[0]=b[0], then sort them by a[1]-b[1].

{1, 11}
{1, 100}
{2, 12}
{11, 22}

该怎么做?

推荐答案

基本上,您要做的是比较内部数组 按字典顺序 (例如字典中单词的排序方式).

Essentially what you want to do is to compare the inner arrays lexicographically (like how words are ordered in a dictionary). Arrays.compare does exactly that.

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

这篇关于按第一列对2d数组进行排序,然后对第二列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆