简体   繁体   English

按第一列然后按第二列对二维数组进行排序

[英]Sort a 2d array by the first column and then by the second one

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

Above array has been sorted as上面的数组已排序为

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

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] .我希望它们首先按a[0]-b[0]排序,如果a[0]=b[0] ,然后按a[1]-b[1]对它们进行排序。

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

How to do that?怎么做?

Essentially what you want to do is to compare the inner arrays lexicographically (like how words are ordered in a dictionary).本质上,您要做的是按字典顺序比较内部 arrays (就像单词在字典中的排序方式一样)。 Arrays.compare does exactly that. Arrays.compare正是这样做的。

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

You can use a chain of comparators as follows:您可以使用如下比较器链:

int[][] arrs = {{1, 100}, {11, 22}, {1, 11}, {2, 12}};

Arrays.sort(arrs, Comparator
        .<int[]>comparingInt(arr -> arr[0]).thenComparing(arr -> arr[1]));

Arrays.stream(arrs).map(Arrays::toString).forEach(System.out::println);

Output: Output:

[1, 11]
[1, 100]
[2, 12]
[11, 22]

See also: Sorting a 2d array in ascending order另请参阅:按升序对二维数组进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM