Is there possibility of sum of ArrayList without looping

后端 未结 13 1434
无人共我
无人共我 2020-11-27 04:24

Is there possibility of sum of ArrayList without looping?

PHP provides sum(array) which will give the sum of array.

The PHP code is

13条回答
  •  不知归路
    2020-11-27 04:47

    This can be done with reduce using method references reduce(Integer::sum):

    Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
            .stream()
            .reduce(Integer::sum)
            .get();
    

    Or without Optional:

    Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
            .stream()
            .reduce(0, Integer::sum);
    

提交回复
热议问题