9

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]
user3354890
  • 367
  • 1
  • 3
  • 10

2 Answers2

27

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
skiwi
  • 66,971
  • 31
  • 131
  • 216
  • @MarounMaroun Yep, looks like its using lambdas – Kevin Bowersox Mar 19 '14 at 09:18
  • That's great!.. Can you explain more about the *mapping*? – Maroun Mar 19 '14 at 09:19
  • @user3354890:- Then you can go with my answer! :) – Rahul Tripathi Mar 19 '14 at 09:26
  • @user3414693 your solution is using loop, in which, OP already mention _"Doing this implicitly with a loop is easy..."_ :( – Baby Mar 19 '14 at 09:27
  • I will accept this solution as the answer, as this was the solution I was ultimately looking for even though it is incompatible with java 7. I'll just have to convince the company to upgrade ;-). – user3354890 Mar 20 '14 at 08:19
  • @user3354890 There are far more stronger arguments than this question & answer though, you should look into all Java 8 features and especially the lambdas and `Stream` API are worth it to upgrade, and probably forgetting some other awesome features on the way. – skiwi Mar 20 '14 at 08:24
1

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

free斩
  • 421
  • 1
  • 6
  • 18