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

huangapple go评论65阅读模式
英文:

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

问题

以下是翻译好的部分:

我想在Java中对一个二维数组进行行和列排序。是否有一种类似于以下Python代码的方法来实现?我有一个名为numbers[][2]的数组。

Python代码:

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

在Java中,我们能否通过Arrays.sort()实现相同的功能?如果可以,我需要传递什么样的比较器?

英文:

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

得分: 1

你可以使用以下代码:

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

这使用了Arrays.sort的一个重载版本,它接收一个Comparator

也许使用普通的Lambda表达式会更好:

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);

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

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定