How to cast from List<Double> to double[] in Java?

kamaci picture kamaci · May 16, 2011 · Viewed 98.9k times · Source

I have a variable like that:

List<Double> frameList =  new ArrayList<Double>();

/* Double elements has added to frameList */

How can I have a new variable has a type of double[] from that variable in Java with high performance?

Answer

Alexis C. picture Alexis C. · Dec 17, 2014

With , you can do it this way.

double[] arr = frameList.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference
double[] arr = frameList.stream().mapToDouble(d -> d).toArray(); //identity function, Java unboxes automatically to get the double value

What it does is :

  • get the Stream<Double> from the list
  • map each double instance to its primitive value, resulting in a DoubleStream
  • call toArray() to get the array.