Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java element-wise sum 2 arrays

Given that I have two arrays in Java, A and B I want to add the elements, element-wise, which results in a sum array. Doing this implicitly with a loop is easy but I was wondering if there was a more elegant solution, perhaps with the guava collections or build in java utils. Or perhaps a python-ish way which makes is easy with list comprehensions.

Example:

A   = [2,6,1,4]
B   = [2,1,4,4]
sum = [4,7,5,8]
like image 610
user3354890 Avatar asked Mar 19 '14 09:03

user3354890


People also ask

How do you sum two arrays in Java?

You cannot use the plus operator to add two arrays in Java e.g. if you have two int arrays a1 and a2, doing a3 = a1 + a2 will give a compile-time error. The only way to add two arrays in Java is to iterate over them and add individual elements and store them into a new array.

How do you sum an element in two arrays?

The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum.

Can you sum arrays in Java?

In order to find the sum of all elements in an array, we can simply iterate the array and add each element to a sum accumulating variable.

Can you add two arrays?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


1 Answers

You can do it like this:

private void sum() {
    int a[] = {2, 6, 1, 4};
    int b[] = {2, 1, 4, 4};

    int result[] = new int[a.length];
    Arrays.setAll(result, i -> a[i] + b[i]);
}

This will first create int result[] of the correct size.

Then with Java 8, released yesterday, the easy part comes:

  • You can do an Arrays.setAll(int[] array, IntUnaryOperator);
  • As IntUnaryOperator you can create a lambda mapping the index to the result, in here we choose to map i to a[i] + b[i], which exactly produces our sum.
  • For very big arrays we can even use Arrays.parallelSetAll
like image 142
skiwi Avatar answered Sep 17 '22 17:09

skiwi