Simple Way to Compute Median in Java

There is no way that I know of to find the median of a list of numbers in the Java framework. The median is the middle value. If there is an even number of values, the median is the middle of these two numbers. Below is a method, along with a supporting method and some tests for computing the median in Java.

public static double Median(ArrayList values)
{
    Collections.sort(values);
 
    if (values.size() % 2 == 1)
	return values.get((values.size()+1)/2-1);
    else
    {
	double lower = values.get(values.size()/2-1);
	double upper = values.get(values.size()/2);
 
	return (lower + upper) / 2.0;
    }	
}

public static ArrayList CreateDoubleList(double ... values)
{
    ArrayList results = new ArrayList();
 
    for (double d : values)
	results.add(d);
    return results;
}
 
System.out.println(2.5==MathUtility.Median(Lists.CreateDoubleList(0,1,2,3,4,5)));
System.out.println(2.0==MathUtility.Median(Lists.CreateDoubleList(0,1,2,3,4)));
System.out.println(2.0==MathUtility.Median(Lists.CreateDoubleList(3,1,2)));
System.out.println(3.0==MathUtility.Median(Lists.CreateDoubleList(3,2,3)));
System.out.println(1.234==MathUtility.Median(Lists.CreateDoubleList(1.234, 3.678, -2.467)));
System.out.println(1.345==MathUtility.Median(Lists.CreateDoubleList(1.234, 3.678, 1.456, -2.467)));

2 Responses to “Simple Way to Compute Median in Java”

  1. hi-ya, I read all your posts, keep them coming.

  2. it was very useful to me .

    thanks

Leave a Reply