With java-8, 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 :
Stream<Double>
from the listDoubleStream
toArray()
to get the array.Guava has a method to do this for you: double[] Doubles.toArray(Collection<Double>)
This isn't necessarily going to be any faster than just looping through the Collection
and adding each Double
object to the array, but it's a lot less for you to write.
You can convert to a Double[]
by calling frameList.toArray(new Double[frameList.size()])
, but you'll need to iterate the list/array to convert to double[]
You can use the ArrayUtils
class from commons-lang to obtain a double[]
from a Double[]
.
Double[] ds = frameList.toArray(new Double[frameList.size()]);
...
double[] d = ArrayUtils.toPrimitive(ds);
As per your question,
List<Double> frameList = new ArrayList<Double>();
First you have to convert List<Double>
to Double[]
by using
Double[] array = frameList.toArray(new Double[frameList.size()]);
Next you can convert Double[]
to double[]
using
double[] doubleArray = ArrayUtils.toPrimitive(array);
You can directly use it in one line:
double[] array = ArrayUtils.toPrimitive(frameList.toArray(new Double[frameList.size()]));
You can use primitive collections from Eclipse Collections and avoid boxing altogether.
DoubleList frameList = DoubleLists.mutable.empty();
double[] arr = frameList.toArray();
If you can't or don't want to initialize a DoubleList
:
List<Double> frames = new ArrayList<>();
double[] arr = ListAdapter.adapt(frames).asLazy().collectDouble(each -> each).toArray();
Note: I am a contributor to Eclipse Collections.
Source: Stackoverflow.com