Karthik Karthik - 5 months ago 54x
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<>();

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?


Try reduce of streams, it should help.


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

This link provides more information on how to use reduce.