How to multiply values in a list using java 8 streams

后端 未结 4 661
长情又很酷
长情又很酷 2020-12-29 18:06

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         


        
4条回答
  •  温柔的废话
    2020-12-29 18:56

    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.

提交回复
热议问题