Java convert Arraylist<Float> to float[]
79,330
Solution 1
Loop over it yourself.
List<Float> floatList = getItSomehow();
float[] floatArray = new float[floatList.size()];
int i = 0;
for (Float f : floatList) {
floatArray[i++] = (f != null ? f : Float.NaN); // Or whatever default you want.
}
The nullcheck is mandatory to avoid NullPointerException
because a Float
(an object) can be null
while a float
(a primitive) cannot be null
at all.
In case you're on Java 8 already and it's no problem to end up with double[]
instead of float[]
, consider Stream#mapToDouble()
(no there's no such method as mapToFloat()
).
List<Float> floatList = getItSomehow();
double[] doubleArray = floatList.stream()
.mapToDouble(f -> f != null ? f : Float.NaN) // Or whatever default you want.
.toArray();
Solution 2
You can use Apache Commons ArrayUtils.toPrimitive()
:
List<Float> list = new ArrayList<Float>();
float[] floatArray = ArrayUtils.toPrimitive(list.toArray(new Float[0]), 0.0F);
Solution 3
Apache Commons Lang to the rescue.
Related videos on Youtube
Author by
lacas
I am from Europe, Hungary. I am currently a php and android programmer.
Updated on March 25, 2022Comments
-
lacas about 2 years
How I can do that?
I have an arraylist, with float elements.
(Arraylist <Float>)
(float[]) Floats_arraylist.toArray()
it is not working.
cannot cast from Object[] to float[]
-
Seva Alekseyev over 13 yearsThe inverse of this: stackoverflow.com/questions/2585907/…
-
bestsss over 13 years
int s=list.size(); float[] a = new float[s]; for (int i=0;i<s;i++) a[i]=list.get(i);
-
Saurabh over 13 yearsDifferent primitive type, but essentially the same question: Creating a byte[] from a List<Byte>
-
-
PawelP over 10 yearsSuch a bummer. That used to be so easy in C#.
-
Mickael Bergeron Néron about 7 yearsIn days like this I hate Java.
-
Hephaestus over 5 yearsLink above is broken. I used the following import:
import org.apache.commons.lang3.ArrayUtils;
-
Galigator almost 3 yearslist.toArray(...) will create an intermediate array... while the simple loop over the list won't.