Java Collection Average average(Collection a)

Here you can find the source of average(Collection a)

Description

Compute the average for a Collection of numeric types

License

Open Source License

Parameter

Parameter Description
a a collection of numeric objects

Return

the average of a

Declaration

public static double average(Collection a) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Collection;

public class Main {
    /**/*from  w w w.  jav  a  2s.  c o  m*/
     * Compute the average for a Collection of numeric types
     * @param a a collection of numeric objects
     * @return the average of a
     */
    public static double average(Collection a) {
        double sum = 0;

        for (Object x : a) {
            if (x instanceof Double) {
                sum += (Double) x;
            } else if (x instanceof Long) {
                sum += (Long) x;
            } else if (x instanceof Integer) {
                sum += (Integer) x;
            } else if (x instanceof Float) {
                sum += (Float) x;
            }
        }

        if (a.size() > 0) {
            return sum / a.size();
        } else {
            return 0;
        }
    }
}

Related

  1. average(Collection col)
  2. average(Collection sizes)
  3. average(Collection values)
  4. average(Collection values)