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

Viewed 699
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?

2 Answers

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

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

Related