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

橙三吉。 提交于 2021-02-10 08:32:23

问题


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].

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

How to do that?


回答1:


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);



回答2:


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:

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

See also: Sorting a 2d array in ascending order



来源:https://stackoverflow.com/questions/65948258/sort-a-2d-array-by-the-first-column-and-then-by-the-second-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!