Is there possibility of sum of ArrayList without looping

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

    Write a util function like

    public class ListUtil{
    
        public static int sum(List list){
          if(list==null || list.size()<1)
            return 0;
    
          int sum = 0;
          for(Integer i: list)
            sum = sum+i;
    
          return sum;
        }
    }
    

    Then use like

    int sum = ListUtil.sum(yourArrayList)
    

提交回复
热议问题