Java Collection Sum sum(Collection collection)

Here you can find the source of sum(Collection collection)

Description

Add all numbers in a collection.

License

Open Source License

Parameter

Parameter Description
N a parameter
collection the collection you want the sum from

Return

the sum of all the entries in the collection (double)

Declaration

public static <N extends Number> double sum(Collection<N> collection) 

Method Source Code

//package com.java2s;

import java.util.Collection;

public class Main {
    /**//  w  w w. j av  a 2 s  .c  o m
     * Add all numbers in a collection.
     *
     * @param <N>
     * @param collection the collection you want the sum from
     * @return the sum of all the entries in the collection (double)
     */
    public static <N extends Number> double sum(Collection<N> collection) {

        double sum = 0;
        for (N number : collection) {
            sum += number.doubleValue();
        }
        return sum;
    }

    public static double sum(double[] c) {
        double r = 0;
        for (double x : c) {
            r += x;
        }
        return r;
    }

    /**
     * Add all numbers in an array.
     *
     * @param <N>
     * @param c the collection you want the sum from
     * @return the sum of all the entries in the collection (float)
     */
    public static float sum(float[] c) {
        float r = 0;
        for (float x : c) {
            r += x;
        }
        return r;
    }

    /**
     * Add all numbers in an array.
     *
     * @param <N>
     * @param c the collection you want the sum from
     * @return the sum of all the entries in the collection (int)
     */
    public static int sum(int[] c) {
        int r = 0;
        for (int x : c) {
            r += x;
        }
        return r;
    }
}

Related

  1. sum(Collection values)
  2. sum(Collection values)
  3. sum(Collection values)
  4. sum(Collection vec)
  5. sum(Collection values)
  6. sum(final Collection values)
  7. sumDouble(Collection collection)
  8. summarizeCollection(Collection collection, String collectionType, String elementType)
  9. sumNumberCollection(Collection numbers)