6

I have two ArrayLists, named A and B, of equal size containing some numbers. Now I want to calculate something like this:

int sum = 0;
for(int i=0; i<A.size() && i<B.size(); i++) {
  sum += A.get(i)*B.get(i);
}

How can I achieve what I am doing above, calculating the sum, by using Java 8 features (streams, lambda expressions, etc) without using any extra user-defined methods?

4
  • 2
    You might get a better answer if you explain why the loop is not acceptable to you, but you can use the rather literal stream translation of that loop with IntStream.range(0, A.size()).map(i -> A.get(i) * B.get(i)).sum(). Commented Jun 28, 2015 at 2:38
  • 1
    Just for good programming measure: I don't see any proof that A and B are the same size. Commented Jun 28, 2015 at 2:39
  • @JeffreyBosboom I have no problems with using loops. I asked it because I am learning Java 8 features, should have included that in the post. Commented Jun 28, 2015 at 2:55
  • 1
    possible duplicate of Iterate two Java-8-Streams together Commented Jun 28, 2015 at 3:48

2 Answers 2

15
int sum = 
    IntStream.range(0, min(a.size(), b.size())
             .map(i -> a.get(i) * b.get(i))
             .sum();
Sign up to request clarification or add additional context in comments.

9 Comments

I think it's multiplication, not addition. a.get(i) + b.get(i) should be a.get(i) * b.get(i)?
That's a neat solution. I hadn't considered emitting the range of indices as a Stream.
@Mubin - It will work "as is" for any collections that support positional access.
@Mubin the IntStream.range generates a Stream of indices, not a Stream of values to be multiplied. All Lists are indexable by integer indexes regardless of contained types.
For using ArrayLists with Double values, I had to use mapToDouble instead of map, otherwise it was giving Type mismatch: cannot convert from double to int
|
0
int sum = IntStream
            .range(0, min(a.size(), b.size())
            .map(i -> 
              (a.get(i).getValue() == null || b.get(i).getValue() == null) ? 0 :
                       (a.get(i).getValue() * b.get(i).getValue()))
            .sum();

Neat Solution!
I had a similar requirement, and I added ternary operator null check. (In my scenario, my lists where of generic type and calculation was done on values within the object which could be null)

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.