javaarraysjava-streamelementwise-operations

How can I do an element-wise sum of several arrays in Java inside a stream?


I want to stream a list of objects, each of which contain a series of integers of the same size. Then I want to do an element-wise sum of all the lists, reulting into a single list of the same size. It should be something like this...

Example:

Object object1;
ArrayList<int> array1 = Arrays.asList(1, 1, 1);
object1.ArrayOfInts = array1;

Object object2;
ArrayList<int> array2 = Arrays.asList(2, 2, 2);
object2.ArrayOfInts = array2; 


ArrayList<Object> listOfObjects = Arrays.asList(object1, object2);


ArrayList<Integer> result = listOfObjects.stream().map(object -> object.ArrayOfInts).sum(...

"result" would be [3, 3, 3].

Any ideas?


Solution

  • Given that all arrays are of the same size, then you can use IntStream

    int[] result = IntStream
            .range(0, listOfObjects.get(0).ArrayOfInts.length) // All are of the same size
            .map(index -> listOfObjects.stream().mapToInt(a -> a.ArrayOfInts[index]).sum())
            .toArray();
    
    [3, 3, 3]