简体   繁体   English

如何求和两个二维数组的元素?

[英]How to sum the elements of two 2d arrays?

I'm trying to add the elements of two two-dimensional arrays with each other, by using the java stream API.我正在尝试使用 java 流 API 将两个二维数组的元素相互添加。
I managed the problem with a one-dimensional array, but I don't know how to proceed further with a two-dimensional array.我用一维数组解决了这个问题,但我不知道如何进一步处理二维数组。

Here is the code to transform:这是要转换的代码:

public static int[][] add(final int[][] m1, final int[][] m2) {
    int[][] e = new int[m2.length][m2[0].length];
    for (int i = 0; i < m1.length; i++) {
        for (int j = 0; j < m1[i].length; j++) {
            e[i][j] = m1[i][j] + m2[i][j];
        }
    }
    return e;
}

And this is the code which I wrote for the same purpose but only with a one-dimensional array :这是我为相同目的编写的代码,但仅使用一维数组

public static int[] addOneDimension(final int[] a, final int b[]) {
    int[] c = IntStream.range(0, a.length)
            .map(i -> a[i] + b[i])
            .toArray();
    return c;
}

In particular, I don't know how to use the map() method on two-dimensional arrays.特别是,我不知道如何在二维数组上使用map()方法。

This can be implemented using IntStream and its methods mapToObj to handle rows and map to handle elements in each row:这可以使用IntStream及其方法mapToObj来处理行和map来处理每一行中的元素:

static int[][] add(int[][] a, int [][] b) {
    return IntStream.range(0, a.length)
                    .mapToObj(i -> add(a[i], b[i])) // int[] is object
                    .toArray(int[][]::new);         // create new 2D array
}
    
static int[] add(int[] a, int[] b) {
    return IntStream.range(0, a.length)
                    .map(i -> a[i] + b[i])  // processing int operands
                    .toArray();             // IntStream.toArray() returns int[]
}

Test测试

int[][] a = {
    {1, 2},
    {3, 4}
};

int[][] b = {
    {10, 20},
    {30, 40}
};

System.out.println("Sum of a + b = ");
Arrays.stream(add(a, b))
      .map(Arrays::toString)
      .forEach(System.out::println);

Output输出

Sum of a + b = 
[11, 22]
[33, 44]

Single-method implementation may be as follows:单方法实现可能如下:

static int[][] add2D(int[][] a, int [][] b) {
    return IntStream
            .range(0, a.length)
            .mapToObj(i -> IntStream
                            .range(0, a[i].length)
                            .map(j -> a[i][j] + b[i][j])
                            .toArray()
            )
            .toArray(int[][]::new);
}

You can use Stream#reduce method to sum the elements of two or more 2d arrays:您可以使用Stream#reduce方法对两个或多个二维数组的元素求和:

public static int[][] sumArrays(int[][]... arrays) {
    // reduce the stream of arrays into a single
    // array by sequentially summing array pairs
    return Arrays.stream(arrays).reduce((a1, a2) -> IntStream
            // iterate over the indices of
            // the rows of the largest array
            .range(0, Math.max(a1.length, a2.length))
            .mapToObj(i -> IntStream
                    // iterate over the indices of
                    // the cells of the largest row
                    .range(0, Math.max(
                            i < a1.length ? a1[i].length : 0,
                            i < a2.length ? a2[i].length : 0))
                    // sum the elements of two rows if exist, or 0 otherwise
                    .map(j -> (i < a1.length && j < a1[i].length ? a1[i][j] : 0)
                            + (i < a2.length && j < a2[i].length ? a2[i][j] : 0))
                    .toArray())
            .toArray(int[][]::new))
            .orElse(null);
}
// test
public static void main(String[] args) {
    int[][] arr1 = {
            {1},
            {1, 1}};

    int[][] arr2 = {
            {2},
            {2, 2},
            {2, 2, 2}};

    int[][] arr3 = {
            {3, 3, 3, 3},
            {3, 3, 3, 3},
            {3, 3, 3, 3},
            {3, 3, 3, 3}};

    int[][] sum = sumArrays(arr1, arr2, arr3);

    // output
    Arrays.stream(sum).map(Arrays::toString).forEach(System.out::println);
    //[6, 3, 3, 3]
    //[6, 6, 3, 3]
    //[5, 5, 5, 3]
    //[3, 3, 3, 3]
}

See also: Sum of 2 different 2d arrays另请参阅: 2 个不同二维数组的总和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM