Java convert Arraylist to float[]

后端 未结 3 915
我在风中等你
我在风中等你 2020-12-15 15:25

How I can do that?

I have an arraylist, with float elements. (Arraylist )

(float[]) Floats_arraylist.toArray()
3条回答
  •  死守一世寂寞
    2020-12-15 15:40

    Loop over it yourself.

    List 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 floatList = getItSomehow();
    double[] doubleArray = floatList.stream()
        .mapToDouble(f -> f != null ? f : Float.NaN) // Or whatever default you want.
        .toArray();
    

提交回复
热议问题