Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply & Sum two ArrayLists in Java8

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?

like image 634
Mubin Avatar asked Jun 28 '15 02:06

Mubin


1 Answers

int sum = 
    IntStream.range(0, min(a.size(), b.size())
             .map(i -> a.get(i) * b.get(i))
             .sum();
like image 189
Brian Goetz Avatar answered Sep 28 '22 00:09

Brian Goetz