Is there possibility of sum of ArrayList without looping

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

    Given that a list can hold any type of object, there is no built in method which allows you to sum all the elements. You could do something like this:

    int sum = 0;
    
    for( Integer i : ( ArrayList<Integer> )tt ) {
      sum += i;
    }
    

    Alternatively you could create your own container type which inherits from ArrayList but also implements a method called sum() which implements the code above.

    0 讨论(0)
  • 2020-11-27 04:40

    Write a util function like

    public class ListUtil{
    
        public static int sum(List<Integer> 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)
    
    0 讨论(0)
  • 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<Double> NUMBERS_FOR_SUM = new ArrayList<Double>(){
             {
                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

    0 讨论(0)
  • 2020-11-27 04:47

    ArrayList is a Collection of elements (in the form of list), primitive are stored as wrapper class object but at the same time i can store objects of String class as well. SUM will not make sense in that. BTW why are so afraid to use for loop (enhanced or through iterator) anyways?

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-27 04:48

    for me the clearest way is this:

    doubleList.stream().reduce((a,b)->a+b).get();
    

    or

    doubleList.parallelStream().reduce((a,b)->a+b).get();
    

    It also use internal loops, but it is not possible without loops.

    0 讨论(0)
提交回复
热议问题