英文:
How to sort a 2d array using the second index for tiebreaks
问题
请注意,您提供的代码部分已被保留,我将为您提供翻译后的代码部分:
Arrays.sort(input, (a, b) -> {
int c1 = a[0];
int c2 = b[0];
if (c1 == c2) return a[1] - b[1];
return c1 - c2;
});
这段代码是用Java中的Lambda表达式对一个二维数组进行排序的示例,如果需要进行二次排序(tiebreak),它会比较第二个元素。如果数组是 { {1,0}, {2,5}, {1,55} }
,排序后会变成 { {1,0}, {1,55}, {2,5} }
。希望这可以帮助您解决问题!
英文:
Anyone know the correct syntax for sorting an 2d array using Lambdas in java where in the need to tiebreak we move on to the second element?
like if the array is { {1,0}, {2,5}, {1,55}}
it becomes {{1,0}, {1,55}, {2,5}}
So Im familair that the syntax for just sorting the array as input follows the syntax of
```java
Arrays.sort(input, (a, b) -> (a[0] - b[0));
```
I have tried some of my own experimental ways around this, such as
```java
Arrays.sort(input, (a,b) ->
int c1 = a[0];
int c2 = b[0];
if(c1 == c2) return a[1] - b[1];
return c1 - c2;
);
but these still have syntax errors in various places. Any help is appreciated!
答案1
得分: 3
在lambda主体包含多个表达式时,需要在lambda主体周围使用括号。此外,应首选Integer.compare
而不是减法(考虑溢出)。
Arrays.sort(input, (a, b) -> {
int c1 = a[0];
int c2 = b[0];
if (c1 == c2) return Integer.compare(a[1], b[1]);
return Integer.compare(c1, c2);
});
这可以简化为使用Comparator
方法。
Arrays.sort(input, Comparator.<int[]>comparingInt(x -> x[0]).thenComparingInt(x -> x[1]));
Arrays.compare
将此数组的字典顺序推广到任意长度的数组(正如Eritrean所提到的)。
Arrays.sort(input, Arrays::compare);
英文:
You need braces around the lambda body when it consists of more than one expression. Also, Integer.compare
should be preferred over subtracting (consider overflow).
Arrays.sort(input, (a, b) -> {
int c1 = a[0];
int c2 = b[0];
if (c1 == c2) return Integer.compare(a[1], b[1]);
return Integer.compare(c1, c2);
});
This can be simplified with Comparator
methods.
Arrays.sort(input, Comparator.<int[]>comparingInt(x -> x[0]).thenComparingInt(x -> x[1]));
Arrays.compare
generalizes this lexicographic order for arrays of any length (as mentioned by Eritrean).
Arrays.sort(input, Arrays::compare);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论