javamatrixmultidimensional-arrayjava-streamaddition

How to sum two 2D arrays elementwise?


I am running into trouble with how to sum two 2D arrays elementwise. I have referenced another post: Java 8 Stream and operation on arrays, and understand how to do this with two 1D arrays but how do you now progress through the rows of a 2D array?

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

I should add that the end goal is to do a threadsafe parallel stream implementation.


Solution

  • Do it like this: It will work on any two int arrays of the same structure. Basically I just iterate the length of the arrays, sum the individual cells, and convert first to a single array and then those to a 2D array.

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

    Prints

    [[6, 8], [10, 12, 15], [7]]