Java – how to sort a two-dimensional array in dictionary order?

Suppose we have a two-dimensional array as follows:

int[][] source = {
  {   3,5,6,1},{   3,3,-6},{  -1,-3,-5,{ 124,43,55,-66}
};

How do we sort multidimensional array sources in dictionary order?

So, as a result, I hope it is:

[ [ -1,-6],[  3,1],[124,-66] ]

Many problems on this website seem to only suggest sorting by the first element or the second, third, etc. of each array, but do not consider the whole array

Solution

Starting with jdk9, there is a named arrays Compare's new method, which allows you to compare two given arrays in dictionary order

For arrays. In the document Short description of compare:

Since you want to modify the source array, use arrays Sort should be enough:

Arrays.sort(source,Arrays::compare);

Since you want a new array as the result, I will use streaming mode:

int[][] sorted = Arrays.stream(source)
                       .sorted(Arrays::compare)
                       .toArray(int[][]::new);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>