Sum, Mean, Median and Standard Deviation Using Lists in Java
August 2, 2011 Leave a comment
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; if (sum > 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)); } }
Recent comments