Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a 2 dimensional array

I've got a 2D array that I'd like to sort into descending order depending on the contents of the first column, however I'd like the array to retain each row and move the second column as the first moves. To put it into an example;

[2, 5]
[4, 18]
[1, 7]
[9, 3]

would be sorted into:

[9, 3]
[4, 18]
[2, 5]
[1, 7]

Thanks.

like image 847
siame Avatar asked Aug 11 '26 09:08

siame


1 Answers

Try this:

    int[][] test = new int[][]{{2,5}, {4,18}, {1,7},{9,3}};
    Arrays.sort(test, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o2[0] - o1[0];
        }
    });

I haven't tested this but it should work. Note you may want to reverse the subtraction to change descending.

like image 127
Amir Raminfar Avatar answered Aug 13 '26 05:08

Amir Raminfar



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!