Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

How to do that?

like image 769
Don Avatar asked Oct 19 '25 14:10

Don


1 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);
like image 76
Sweeper Avatar answered Oct 22 '25 02:10

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!