Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntStream to sum a 2D array

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();
like image 777
jdpruitt Avatar asked Mar 17 '16 19:03

jdpruitt


1 Answers

You just need to map each sub-array to an int by taking the first element:

import java.util.*;
import java.util.stream.*; 

class Test {
    public static void main(String args[]) {
        int[][] data = {
            { 1, 2, 3 },
            { 4, 5, 6 }
        };

        int sum = Arrays.stream(data)
                        .mapToInt(arr -> arr[0])
                        .sum();
        System.out.println(sum); // 5, i.e. data[0][0] + data[1][0]
    } 
}

In other words:

  • Transform data to a Stream<int[]> (i.e. a stream of simple int arrays)
  • Map each array to its first element, so we end up with an IntStream
  • Sum that stream

I prefer this approach over the approaches using range, as there seems no need to consider the indexes of the sub-arrays. For example, if you only had an Iterable<int[]> arrays you could still use StreamSupport.stream(arrays.spliterator(), false).mapToInt(arr -> arr[0]).sum(), whereas the range approach would require iterating multiple times.

like image 148
Jon Skeet Avatar answered Sep 22 '22 15:09

Jon Skeet