Java Collection Median median(Collection values)

Here you can find the source of median(Collection values)

Description

median

License

Open Source License

Declaration

public static Double median(Collection<Double> values) 

Method Source Code


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

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class Main {
    public static Double median(Collection<Double> values) {
        List<Double> filteredValues = filterNulls(values);

        if (filteredValues.size() == 0)
            return 0.;
        if (filteredValues.size() == 1)
            return filteredValues.get(0);

        Collections.sort(filteredValues);

        if (filteredValues.size() % 2 == 0) {
            return (filteredValues.get(filteredValues.size() / 2)
                    + filteredValues.get(filteredValues.size() / 2 - 1)) / 2.;
        } else {//from   ww  w .j  a va2s .  c om
            return filteredValues.get(filteredValues.size() / 2);
        }
    }

    private static List<Double> filterNulls(Collection<Double> values) {
        List<Double> result = new ArrayList<>();
        for (Double value : values) {
            if (value != null)
                result.add(value);
        }

        return result;
    }
}

Related

  1. median00(Collection coll)