Question

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]
Was it helpful?

Solution

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

OTHER TIPS

You can use java8 stream and operation on array like this:

//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...
int[] result = new int[a.length];
IntStream.range(0, a.length)
     .forEach(i -> result[i] = a[i] + b[i]);

The answer in java8

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top