10

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]
6
  • 2
    Using loop is very elegant. Commented Mar 19, 2014 at 9:16
  • 1
    @Eel Lee did you read the text or only the title? Commented Mar 19, 2014 at 9:18
  • 2
    like Maroun said, using loop is the most elegant way to do any operation on array Commented Mar 19, 2014 at 9:18
  • 1
    @RafaEl Not neccessarily since Java 8. Commented Mar 19, 2014 at 9:19
  • ok, ignore my comment. Im going to explore java 8 Commented Mar 19, 2014 at 9:22

2 Answers 2

28

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
Sign up to request clarification or add additional context in comments.

6 Comments

@MarounMaroun Yep, looks like its using lambdas
That's great!.. Can you explain more about the mapping?
@user3354890:- Then you can go with my answer! :)
@user3414693 your solution is using loop, in which, OP already mention "Doing this implicitly with a loop is easy..." :(
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 ;-).
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.