Java 2D数组上的流操作

问题描述

我在如何对两个2D数组逐元素求和时遇到麻烦。我已经引用了另一个post,并了解了如何使用两个1D数组来执行此操作,但是现在如何在2D数组的行中进行遍历?

    //in this example a[] and b[] are Square matrices
    int[] A = [n][n]
    int[] B = [n][n]
    
    int[] result = new int[A.length][A[0].length];
    
    //I kNow this only adds the first rows together.
    //How do I Now iterate through the rows to sum the entire matrix elementwise
    result[0]=IntStream.range(0,A.length).map(i->A[0][i]+B[0][i]).toArray();

我应该补充一点,最终目标是执行线程安全的并行流实现。

解决方法

执行以下操作:它将在相同结构的任何两个int数组上工作。基本上,我只是迭代数组的长度,对单个单元格求和,然后先转换为单个数组,然后再转换为2D数组。

  • MapToObj是必需的,因为第二个IntStream不是int而是流对象。

  • 然后我需要的只是一个map,因为我要对第二个IntStream进行操作。

  • 所有这些都是用于获取数组值的简单索引。

ints

打印

int[][] a = { { 1,2 },{ 3,4,5 },{3} };
int[][] b = { { 5,6 },{ 7,8,10 },{4} };

int[][] sum = IntStream.range(0,a.length)
        .mapToObj(r -> IntStream.range(0,a[r].length)
                .map(c -> a[r][c] + b[r][c]).toArray())
        .toArray(int[][]::new);

System.out.println(Arrays.deepToString(sum));
,

您可以按元素求和多个不同大小的锯齿状二维数组,如下所示:

public static void main(String[] args) {
    int[][] a = {{3,3,3},{3,3}};
    int[][] b = {{2},{2}};
    int[][] c = {{1,1},{1,1,1}};

    int[][] s = sumArrays(a,b,c);

    System.out.println(Arrays.deepToString(s));
    // [[6,3],[6,[4,1]]
}
public static int[][] sumArrays(int[][]... arrays) {
    return Arrays.stream(arrays)
          // sequential summation of array pairs
          .reduce((arr1,arr2) -> IntStream
              // iterate over the indexes of the rows of the max array
              .range(0,Math.max(arr1.length,arr2.length))
              // summation of two rows
              .mapToObj(i -> {
                  // at least one row should be present
                  if (arr1.length <= i)
                    return arr2[i];
                  else if (arr2.length <= i)
                    return arr1[i];
                  else // both rows are present
                    return IntStream
                      // iterate over the indices of the max row
                      .range(0,Math.max(arr1[i].length,arr2[i].length))
                      // the sum of two elements if present,or 0 otherwise
                      .map(j -> (arr1[i].length <= j ? 0 : arr1[i][j])
                              + (arr2[i].length <= j ? 0 : arr2[i][j]))
                      // cumulative row
                      .toArray();
              }) // cumulative array
              .toArray(int[][]::new))
          // or an empty array otherwise
          .orElse(new int[0][]);
}

另见:Sum of 2 different 2D arrays