Karthik Karthik - 2 years ago 249
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download