Java ArrayList Average getAverageOfList(ArrayList values)

Here you can find the source of getAverageOfList(ArrayList values)

Description

Gets the average of a list of values semi-intelligently by removing outliers.

License

Open Source License

Parameter

Parameter Description
values List of double values to get outlers from.

Return

The average from the data set.

Declaration

public static double getAverageOfList(ArrayList<Double> values) 

Method Source Code


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

import java.util.ArrayList;

public class Main {
    /**//from w  ww .ja v a  2  s.c  o m
     * Gets the average of a list of values semi-intelligently by removing outliers.
     *
     * @param values List of double values to get outlers from.
     * @return The average from the data set.
     */
    public static double getAverageOfList(ArrayList<Double> values) {
        int amountOutliers = 0;
        double addedUp = 0;
        for (int index = 0; index < values.size(); index++) {
            if (isOutlier(index, values)) {
                amountOutliers++;
                addedUp += values.get(index);
            }
        }
        return addedUp / (values.size() - amountOutliers);
    }

    /**
     * This method looks at the data set and if there is a value that is 20 numbers higher than either the left, it
     * is an outlier.
     *
     * @param index  The index to test.
     * @param values The data set.
     * @return
     */
    public static boolean isOutlier(int index, ArrayList<Double> values) {
        if (values.size() <= 1) {
            return true;
        }
        //There are 2 edge cases one must account for. The first index and the last index.
        if (index == 0) {
            return isRightOutlier(index, values);
        } else if (index == values.size() - 1) {
            return isLeftOutlier(index, values);
        } else {
            return isRightOutlier(index, values) || isLeftOutlier(index, values);
        }
    }

    /**
     * This is simply just a utility method for isOutlier
     *
     * @param index
     * @param values
     * @return
     */
    private static boolean isRightOutlier(int index, ArrayList<Double> values) {
        double currentValue = values.get(index);
        double valueToRight = values.get(index + 1);
        return Math.abs(currentValue - valueToRight) > 20;
    }

    /**
     * This is simply just a utility method for isOutlier
     *
     * @param index
     * @param values
     * @return
     */
    private static boolean isLeftOutlier(int index, ArrayList<Double> values) {
        double currentValue = values.get(index);
        double valueToLeft = values.get(index - 1);
        return Math.abs(currentValue - valueToLeft) > 20;
    }
}

Related

  1. average(ArrayList nums)
  2. average(ArrayList array)
  3. averageInColumns(ArrayList lines)
  4. getAverage(ArrayList data)
  5. getAverage(ArrayList values)