【问题标题】:Sort a 2d array by the first column and then by the second one按第一列然后按第二列对二维数组进行排序
【发布时间】:2021-05-03 00:08:44
【问题描述】:
int[][] arrs = {{1, 100}, {11, 22}, {1, 11}, {2, 12}};
Arrays.sort(arrs, (a, b) -> (a[0] - b[0]));

以上数组已排序为

{1, 100}
{1, 11}
{2, 12}
{11, 22}

我希望它们首先按a[0]-b[0] 排序,如果是a[0]=b[0],然后按a[1]-b[1] 排序。

{1, 11}
{1, 100}
{2, 12}
{11, 22}

怎么做?

【问题讨论】:

    标签: java arrays sorting multidimensional-array


    【解决方案1】:

    您可以使用如下的比较器链:

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

    输出:

    [1, 11]
    [1, 100]
    [2, 12]
    [11, 22]
    

    另见:Sorting a 2d array in ascending order

    【讨论】:

      【解决方案2】:

      基本上你想要做的是比较内部数组lexicographically(就像单词在字典中的排序方式一样)。 Arrays.compare 正是这样做的。

      Arrays.sort(arrs, Arrays::compare);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-07
        • 1970-01-01
        • 2017-06-17
        • 2011-10-25
        • 2014-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多