您可以按元素对多个不同大小的锯齿状二维数组进行求和,如下所示:
public static void main(String[] args) {
int[][] a = {{3, 3, 3}, {3, 3, 3}, {3, 3, 3}};
int[][] b = {{2}, {2}};
int[][] c = {{1, 1}, {1, 1}, {1, 1, 1, 1}};
int[][] s = sumArrays(a, b, c);
System.out.println(Arrays.deepToString(s));
// [[6, 4, 3], [6, 4, 3], [4, 4, 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