Multiply and sum two arrays in Java8

I have two ArrayLists named A and B, an 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 by calculating the sum using Java 8 functions (streams, lambda expressions, etc.) without using any additional custom methods?

+4
source share
1 answer
int sum = 
    IntStream.range(0, min(a.size(), b.size())
             .map(i -> a.get(i) * b.get(i))
             .sum();
+13
source

All Articles