1. The purpose of this post

This post would demo how to use apache commons math library to do common statistics job(min/max/mean/median/percentile/quantiles) with java.

2. Environments

  • Java 1.8+

3. The solution

3.1 Add apache commons math to your POM.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.6.1</version>
</dependency>

3.2 Write a test

import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;

import java.util.stream.IntStream;

/**
 * Created on 2019/5/13.
 */
public class TestDescrptiveStatistics  {

    public static void main(String[] args) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        
        IntStream.rangeClosed(1, 10).forEach(i->stats.addValue(i));//add 1,2,3,4,5,6,7,8,9,10 to stats

        System.out.println("max value "+stats.getMax());//max value 10.0

        System.out.println("min value "+stats.getMin());//min value 1.0

        System.out.println("mean value "+stats.getMean());//mean value 5.5

        System.out.println("75% value "+stats.getPercentile(75));//75% value 8.25

        System.out.println("25% value "+stats.getPercentile(25));//25% value 2.75

        System.out.println(stats);
        /**
         n: 10
         min: 1.0
         max: 10.0
         mean: 5.5
         std dev: 3.0276503540974917
         median: 5.5
         skewness: 0.0
         kurtosis: -1.2000000000000002
         */
    }
}

3.3 Run the code

we would get this:

max value 10.0
min value 1.0
mean value 5.5
75% value 8.25
25% value 2.75
DescriptiveStatistics:
n: 10
min: 1.0
max: 10.0
mean: 5.5
std dev: 3.0276503540974917
median: 5.5
skewness: 0.0
kurtosis: -1.2000000000000002

4. Conclusion

You can get more information by view the this document and this page.