Issue
Assuming we have a two-dimensional array as follows:
int[][] source = {
{ 3, 5, 6, 1},
{ 3, 3, 5, -6},
{ -1, -3, -5, -6},
{ 124, 43, 55, -66}
};
how do we sort the multidimensional array source
lexicographically?
So, as a result, I'd expect it to be:
[ [ -1, -3, -5, -6],
[ 3, 3, 5, -6],
[ 3, 5, 6, 1],
[124, 43, 55, -66] ]
a lot of questions on this site seem to only suggest sorting by the first element of each array or second, third etc. but not taking in consideration the entire array.
Solution
As of JDK9, there's a new method called Arrays.compare
which allows you to compare two given arrays lexicographically.
Short description of Arrays.compare
from the documentation:
If the two arrays share a common prefix then the lexicographic comparison is the result of comparing two elements, as if by Integer.compare(int, int), at an index within the respective arrays that is the prefix length. Otherwise, one array is a proper prefix of the other and, lexicographic comparison is the result of comparing the two array lengths.
Given you want to modify the source
array then using Arrays.sort
should suffice:
Arrays.sort(source, Arrays::compare);
Given you want a new array as a result then I'd go the stream way:
int[][] sorted = Arrays.stream(source)
.sorted(Arrays::compare)
.toArray(int[][]::new);
Answered By - Ousmane D.
Answer Checked By - Pedro (JavaFixing Volunteer)