Is there possibility of sum of ArrayList without looping

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

    You can use apache commons-collections API.

    class AggregateClosure implements org.apache.commons.collections.Closure {
            int total = 0;
    
            @Override
            public void execute(Object input) {
                if (input != null) {
                    total += (Integer) input;
                }
            }
    
            public int getTotal() {
                return total;
            }
        }
    

    Then use this closure as shown below:

    public int aggregate(List aList) {
            AggregateClosure closure = new AggregateClosure();
            org.apache.commons.collections.CollectionUtils.forAllDo(aList, closure);
            return closure.getTotal();
    }
    

提交回复
热议问题