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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With