Sure, here’s the translation: java 二维数组次要排序

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

java 2d array secondary sort

问题

我想对以下的二维数组进行排序,使得每行的第一个索引递增,如果两行的第一个索引相同,则第二个索引也按递增排序。例如:
给定:

int[][] arr = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};

我希望得到 arr = {{1,1},{1,2},{1,3},{1,4},{1,5},{2,1},{2,2},{2,3},{2,4},{2,5}};

我已经成功通过以下方式按第一个索引排序:

Arrays.sort(arr, Comparator.comparingInt(arr -> arr[0]));

现在我的想法是将其拆分为子数组,对它们进行排序,然后将它们合并在一起,但我真的想知道是否有更好的方法,我可能不知道。(也许甚至可以使用比较器,提前谢谢您的帮助)

英文:

I want to sort the following 2D array so, that the first index of each row is ascending and if it is the same in 2 rows, that the second index also is sorted ascending. Example:
given:

int[][] arr = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};

I want it to be arr = {{1,1},{1,2},{1,3},{1,4},{1,5},{2,1},{2,2},{2,3},{2,4},{2,5}};

It worked for me to sort by first index using:

Arrays.sort(arr, Comparator.comparingInt(arr -> arr[0]));

Now my idea was to cut it down into sub-arrays, sort them and merge them back together, but i really wanted to know if there is a better way to do it I am not aware of. ( maybe even using the comparator, thx in advance )

答案1

得分: 3

你可以通过使用 thenComparing 为第一个比较器添加第二个比较器,这基本上会导致这样的行为:如果第一个比较器返回相等的结果,则使用第二个比较器来解决平局:

int[][] arr2 = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};

Comparator<int[]> first = Comparator.comparingInt(a -> a[0]);
Comparator<int[]> second = Comparator.comparingInt(a -> a[1]);

Arrays.sort(arr2, first.thenComparing(second));

for (int i = 0; i < arr2.length; i++) {
    System.out.println(arr2[i][0] + "," + arr2[i][1]);
}

还可以通过使用 thenComparingInt 来创建更简洁的比较器版本:

Comparator<int[]> cp = Comparator.<int[]>comparingInt(a -> a[0]).thenComparingInt(a -> a[1]);
英文:

you can add a second comparator to the first one by using thenComparing, which basically leads to a behaviour that if the first comparator returns an equal result the second comparator is used to break the tie:

        int[][] arr2 = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};

        Comparator&lt;int[]&gt; first = Comparator.comparingInt(a -&gt; a[0]);
        Comparator&lt;int[]&gt; second = Comparator.comparingInt(a -&gt; a[1]);

        Arrays.sort(arr2, first.thenComparing(second));

        for(int i = 0; i&lt; arr2.length; i++){
            System.out.println(arr2[i][0] + &quot;,&quot; + arr2[i][1]);
        }

it is also possible to create a more succinct version of the comparator, by using thenComparingInt:

Comparator&lt;int[]&gt; cp = Comparator.&lt;int[]&gt;comparingInt(a -&gt; a[0]).thenComparingInt(a -&gt; a[1]);

huangapple
  • 本文由 发表于 2020年4月8日 03:35:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/61088049.html
匿名

发表评论

匿名网友

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

确定