Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum two arrays element-by-element in Java

Tags:

java

arrays

What is the easiest way to sum two arrays element-by-element?

I know that you can use a for loop such as the following:

int[] a = {0, 1, 2};
int[] b = {3, 4, 5};
int[] c = new int[a.length];
for (int i = 0; i < a.length; ++i) {
    c[i] = a[i] + b[i];
}

But in languages such as MATLAB, you can do the element-by-element array sum by just writing c = a + b. Is there an easy way to do this in Java?

The method that comes to mind is using the RealVector class from Apache Commons Math, but that method is rather verbose.

like image 909
I Like to Code Avatar asked Sep 04 '13 15:09

I Like to Code


People also ask

How do you add two array elements?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

How do you sum up an array of elements?

S = sum( A ) returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column.


2 Answers

There's certainly nothing to enable this in the language. I don't know of anything in the standard libraries either, but it's trivial to put the code you've written into a utility method which you can call from anywhere you need it.

like image 189
Jon Skeet Avatar answered Oct 25 '22 03:10

Jon Skeet


One more answer, using streams and providing a more generic solution:

import org.junit.Assert;
import org.junit.Test;

import java.util.function.IntBinaryOperator;
import java.util.stream.IntStream;

public class SOTest {

    @Test
    public void test() {
        int[] a = {0, 1, 2};
        int[] b = {3, 4, 5};

        int[] sum = applyOn2Arrays((x, y) -> x + y, a, b);
        int[] diff = applyOn2Arrays((x, y) -> x - y, a, b);
        int[] mult = applyOn2Arrays((x, y) -> x * y, a, b);


        Assert.assertArrayEquals(new int [] {3,5,7}, sum);
        Assert.assertArrayEquals(new int [] {-3,-3,-3}, diff);
        Assert.assertArrayEquals(new int [] {0,4,10}, mult);
    }

    private int[] applyOn2Arrays(IntBinaryOperator operator, int[] a, int b[]) {
        return IntStream.range(0, a.length)
                .map(index -> operator.applyAsInt(a[index], b[index]))
                .toArray();
    }
}
like image 41
Benoit Avatar answered Oct 25 '22 03:10

Benoit