# Sum, Mean, Median and Standard Deviation Using Lists in Java

August 2, 2011 4 Comments

Well, I needed methods for sum, mean, median, and standard deviation in Java using Lists, so I coded them. Probably is not the most beautiful code that you've ever seen but it works.import java.util.*; class methods { public int sum (List<Integer> a){ if (a.size() > 0) { int sum = 0; for (Integer i : a) { sum += i; } return sum; } return 0; } public double mean (List<Integer> a){ int sum = sum(a); double mean = 0; mean = sum / (a.size() * 1.0); return mean; } public double median (List<Integer> a){ int middle = a.size()/2; if (a.size() % 2 == 1) { return a.get(middle); } else { return (a.get(middle-1) + a.get(middle)) / 2.0; } } public double sd (List<Integer> a){ int sum = 0; double mean = mean(a); for (Integer i : a) sum += Math.pow((i - mean), 2); return Math.sqrt( sum / ( a.size() - 1 ) ); // sample } } class t { public static void main (String[]args) { methods m = new methods(); List<Integer> c = Arrays.asList(2,49,11,44,88,1,1,5,33,88,5,44,2,44,44,132,6,2,22,22,5,1,22,22); Collections.sort(c); System.out.println(m.median(c)); System.out.println(m.mean(c)); System.out.println(m.sd(c)); } }Advertisements

Your mean function has a bug — what happens if all the entries in the input list are negative?

Yea, good catch. Thanks.

The standard deviation has 2 bugs with it. The first bug is that int sum = 0 should be a double because it looses the precision and can return inaccurate answers. The second bug is return Math.sqrt(sum / (a.size() – 1)) should not have the -1. Great job over all it helped a lot!

Thanks for your comment. Please refer to Bessel’s correction to understand why this a.size-1 is there: “

In statistics, Bessel’s correction, named after Friedrich Bessel, is the use of n − 1 instead of n in the formula for the sample variance and sample standard deviation, where n is the number of observations in a sample: it corrects the bias in the estimation of the population variance“. This is the SD of a sample, and therefore it uses the N-1, and that is why there is a comment “sample” on the very same line.