I want to sort the following 2D array so, that the first index of each row is ascending and if it is the same in 2 rows, that the second index also is sorted ascending. Example: given:
int[][] arr = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};
I want it to be arr = {{1,1},{1,2},{1,3},{1,4},{1,5},{2,1},{2,2},{2,3},{2,4},{2,5}};
It worked for me to sort by first index using:
Arrays.sort(arr, Comparator.comparingInt(arr -> arr[0]));
Now my idea was to cut it down into sub-arrays, sort them and merge them back together, but i really wanted to know if there is a better way to do it I am not aware of. ( maybe even using the comparator, thx in advance )
you can add a second comparator to the first one by using
thenComparing
, which basically leads to a behaviour that if the first comparator returns an equal result the second comparator is used to break the tie:it is also possible to create a more succinct version of the comparator, by using
thenComparingInt
: