Is there possibility of sum of ArrayList without looping

后端 未结 13 1399
无人共我
无人共我 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:40

    This link shows three different ways how to sum in java, there is one option that is not in previous answers using Apache Commons Math..

    Example:

    public static void main(String args []){
        List NUMBERS_FOR_SUM = new ArrayList(){
             {
                add(5D);
                add(3.2D);
                add(7D);
             }
        };
        double[] arrayToSume = ArrayUtils.toPrimitive(NUMBERS_FOR_SUM
                .toArray(new Double[NUMBERS_FOR_SUM.size()]));    
        System.out.println(StatUtils.sum(arrayToSume));
    
    }
    

    See StatUtils api

提交回复
热议问题