IntStream to sum a 2D array

Viewed 2582

What is the syntax for using IntStream to sum a range of elements in a 2D array?

For a 1D array, I use the following syntax:

int totalElementsInArray = 0;

totalElementsInarray = IntStream.of(myArray).sum();

So for instance, say I have a 2D array:

int[][] my2DArray = new int[17][4];

What is the syntax when using IntStream for summing columns 0-16 on row 0?

int totalElementsInArray = 0;

totalElementsInarray = IntStream.of(my2DArray[0 through 16][0]).sum();
4 Answers
    int[][] data = {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
    };

    int total = Arrays.stream(data)
            .mapToInt(arr -> Arrays.stream(arr).sum())
            .sum();
    System.out.println(total);
Related