# 如何在Java中对二维数组进行逐行升序和逐列降序排序？

go评论64阅读模式

How can we sort both row-wise ascending and column-wise descending of 2D arrays in Java?

# 问题

Python代码：

``````# 首先根据索引0进行排序；如果它们匹配，则根据索引1进行反向排序
numbers.sort(key=lambda x: (x[0], -x[1]))
``````

I would like to sort a 2D array both row wise and column wise in Java. Is there a way to do that similar to following python code. I have array as numbers;

python code

``````# it first sorts based on index 0; if they match, it reverse sort based on index 1
numbers.sort(key: lambda x:(x[0], -x[1]))
``````

Can we achieve the same in Java through Arrays.sort(), if yes, what will be the comparator that I need to pass ?

# 答案1

``````Arrays.sort(
numbers,
Comparator.comparing((int[] x) -> x[0])
.thenComparing(
(int[] x) -> x[1],
Comparator.<Integer>naturalOrder().reversed()));
``````

``````Arrays.sort(
numbers,
(a, b) -> a[0] < b[0] ? -1 : a[0] > b[0] ?  1 :
a[1] < b[1] ?  1 : a[1] > b[1] ? -1 : 0);
``````

You can use the following code:

``````Arrays.sort(
numbers,
Comparator.comparing((int[] x) -&gt; x[0])
.thenComparing(
(int[] x) -&gt; x[1],
Comparator.&lt;Integer&gt;naturalOrder().reversed()));
``````

This uses the overload of `Arrays.sort` that receives a `Comparator`.

Maybe using a plain lambda expression is better:

``````Arrays.sort(
numbers,
(a, b) -&gt; a[0] &lt; b[0] ? -1 : a[0] &gt; b[0] ?  1 :
a[1] &lt; b[1] ?  1 : a[1] &gt; b[1] ? -1 : 0);
``````

• 本文由 发表于 2020年10月5日 09:46:29
• 转载请务必保留本文链接：https://go.coder-hub.com/64201514.html
• java

go 57

go 69

go 64

go 65