Karthik Karthik - 7 months ago 80
Java Question

How to multiply values in a list using java 8 streams

Is there a sum() equivalent method in stream which can perform multiplication of values given in a stream?

I've a list of Integers like this :

List<Integer> listOfIntegers = new ArrayList<>();
listOfIntegers.addAll(Arrays.asList(1,4,2,7,5));


I'm able to get the sum of all the integers, but unable to find an API which can multiply the values and give the output.

listOfIntegers.stream().mapToInt(a -> a).sum();


If I try to use forEach to do it, then I cannot store the result as only final variables are allowed to be used inside it.

Is there any alternative to this?

Answer

Try reduce of streams, it should help.

Like:

listOfIntegers.stream().reduce(1, (a, b) -> a * b)

This link provides more information on how to use reduce.