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
One thing to keep in mind when multiplying an unknown number of ints
is the possibility of overflows. Rather than (a,b) -> a*b
, it is safer to use Math::multiplyExact
, which will throw an exception on overflow:
listOfIntegers.stream().mapToInt(x->x).reduce(1, Math::multiplyExact);
Alternatively, you can accommodate large results by reducing on BigInteger
:
listOfIntegers.stream()
.map(BigInteger::valueOf)
.reduce(BigInteger.ONE, BigInteger::multiply);
Reduction with an identity will return 1
or BigInteger.ONE
if the list is empty, which may not be what you want. If you wish to handle the case of an empty list, remove the first argument to reduce
and then deal with the resulting Optional
.