问题
int[][] arrs = {{1, 100}, {11, 22}, {1, 11}, {2, 12}};
Arrays.sort(arrs, (a, b) -> (a[0] - b[0]));
Above array has been sorted as
{1, 100}
{1, 11}
{2, 12}
{11, 22}
I want them to be sorted by a[0]-b[0]
first and if a[0]=b[0]
, then sort them by a[1]-b[1]
.
{1, 11}
{1, 100}
{2, 12}
{11, 22}
How to do that?
回答1:
Essentially what you want to do is to compare the inner arrays lexicographically (like how words are ordered in a dictionary). Arrays.compare does exactly that.
Arrays.sort(arrs, Arrays::compare);
回答2:
You can use a chain of comparators as follows:
int[][] arrs = {{1, 100}, {11, 22}, {1, 11}, {2, 12}};
Arrays.sort(arrs, Comparator
.<int[]>comparingInt(arr -> arr[0]).thenComparing(arr -> arr[1]));
Arrays.stream(arrs).map(Arrays::toString).forEach(System.out::println);
Output:
[1, 11]
[1, 100]
[2, 12]
[11, 22]
See also: Sorting a 2d array in ascending order
来源:https://stackoverflow.com/questions/65948258/sort-a-2d-array-by-the-first-column-and-then-by-the-second-one