Suppose I have a 2D integer array of
int[][] arr = new int [][] {
{1,1},
{2,222},
{3,32},
{4,13},
{5,1144},
{6,111},
{7,12341},
{8,111}
};
I want to sort this array in an increasing order of second element of each row.
[[1, 1], [4, 13], [3, 32], [8, 111], [6, 111], [2, 222], [5, 1144], [7, 12341]]
But notice, when the second element's values are same as in
[8, 111] and [6, 111]
The sorting order reversed.
So here is what I attempted
Arrays.sort(arr, (a,b) -> a[1]==b[1]? b[1]-a[1]: a[1]-b[1]);
Whenever second elements are equal, reverse the sorting order to descending order, otherwise keep the ascending order.
After running this code, I get a result of
[[1, 1], [4, 13], [3, 32], [6, 111], [8, 111], [2, 222], [5, 1144], [7, 12341]]
Notice how the
[6, 111], [8, 111]
are still in the wrong order.
a[1]==b[1]? b[1]-a[1] :a[1]-b[1]will always be0ora[1]-b[1](a[1]==b[1]? b[1]-a[1]is always0)Arrays.sort(arr, (a,b) -> a[1]==b[1]? b[0]-a[0]: a[1]-b[1]);If second elements are equal, compare first elements i.e. elements at 0th index.