Search code examples
javaarraysstatisticsapache-commons-math

How to create List<Double> fromapache's common math DescriptiveStatistics<Double>?


I have a variable DescriptiveStatistics stats from which I would like to create Double array. Using the following code:

import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
//...
DescriptiveStatistics stats;
//...
Arrays.asList(stats.getValues())

I get List<double[]> not List<Double>. stats.getValues() returns double[].

How can I fix that and get a List<Double> from this DescriptiveStatistics ?


Solution

  • As per method signature of Arrays.asList() that returns a List of type as passed in arguments.

    public static <T> List<T> asList(T... a)
    

    For example:

    double[] array=new double[]{1,2,3};
    List<double[]> list=Arrays.asList(array); // Here T is `double[]` List of size 1
    
    ...
    
    double[][] array = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } };
    List<double[]> list=Arrays.asList(array); // Here T is `double[]` List of size 2
    
    ...
    
    List<Double> list=Arrays.asList(1.0,2.0,3.0); // Here T is double List of size 3
    

    Root cause:

    Since array itself is an Object and in your case double[] is treated as single object, not as array of double as per Generic hence List<double[]> is returned instead of List<Double>.

    Solution 1

    You can solve it by simple classic code:

    double[] array = new double[] { 1, 2, 3 };
    List<Double> list = new ArrayList<Double>();
    for (double d : array) {
        list.add(d);
    }
    

    Solution 2

    Simply change the return type of the method stats.getValues() from double[] to Double[]

    Double[] array = new Double[] { 1.0, 2.0, 3.0 };
    List<Double> list = Arrays.asList(array);