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 mapi
toa[i] + b[i]
, which exactly produces our sum. - For very big arrays we can even use
Arrays.parallelSetAll