【问题标题】:Sorting a 2d array in Java在Java中对二维数组进行排序
【发布时间】:2021-07-14 04:50:16
【问题描述】:

我很难弄清楚一行代码对二维整数数组进行排序的细节。

正在排序的数组是一个数组,其中的数组只有两个数字,我试图弄清楚(a, b) 是否指的是两个单独的二维数组,如果(a[0] , b[0]) 指的是二维内的数字数组?

Arrays.sort(sortedIntervals, (a, b) -> Integer.compare(a[0], b[0]));

【问题讨论】:

    标签: java arrays sorting multidimensional-array


    【解决方案1】:

    你可以使用key extractorcomparator chaining

    int[][] arr2d = {{1, 3, 6}, {1, 2, 3}, {0, 2, 3}};
    
    // sorting the rows of a 2d array first by
    // the first column, then by the second column
    Arrays.sort(arr2d, Comparator
            .<int[]>comparingInt(row -> row[0])
            .thenComparingInt(row -> row[1]));
    
    System.out.println(Arrays.deepToString(arr2d));
    // [[0, 2, 3], [1, 2, 3], [1, 3, 6]]
    

    【讨论】:

      【解决方案2】:

      Arrays.sort(sortedIntervals, (a,b) -> Integer.compare(a[0] , b[0]));

      如您所见,see here 只有一种方法比较:compare(int,int)。所以a[0] 必须是一个 int(或 java.lang.Integer,分别)。

      因为只有一种方法接受 lambda 作为第二个参数,所以它必须是 this method。而它的 javadoc sais ab 是数组的直接元素 sortedIntervalsab 必须是一个整数数组。

      所以除了sortedIntervals 是一个 2dim 整数数组之外,别无选择。由于我们可以访问 a[0] 和 b[0],我们可以预期 sortedIntervals 的所有直接元素在它们的第一个位置都可以转换为 int

      我们也可以预测

      int[][] sortedIntervals ={{},{}}; 
      int[][] sortedIntervals ={{6},{}}; 
      int[][] sortedIntervals ={{},{6}}; 
      

      将始终在 lambda 中抛出 ArrayIndexOutOfBoundsException,因为索引 0 至少在其中一个元素中不存在。

      【讨论】:

        猜你喜欢
        • 2013-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-17
        • 1970-01-01
        • 2017-05-25
        • 2015-09-17
        相关资源
        最近更新 更多