Honestly: there's no good built-in way to do this with streams. Sorry, but it's the truth.
If you can live with a double[]
, you can use floatList.stream().mapToDouble(f -> f.doubleValue()).toArray()
, but that's probably not what you're hoping for.
If you want to do it with streams, you'll need to write your own custom resizing list type and collect to it, but nothing short of that is going to work. You'd have to write something like
float[] toFloatArray(Collection<Float> collection) {
class FloatArray {
int size;
float[] array;
FloatArray() {
this.size = 0;
this.array = new float[10];
}
void add(float f) {
if (size == array.length) {
array = Arrays.copyOf(array, array.length * 2);
}
array[size++] = f;
}
FloatArray combine(FloatArray other) {
float[] resultArray = new float[array.length + other.array.length];
System.arraycopy(this.array, 0, resultArray, 0, size);
System.arraycopy(other.array, 0, resultArray, size, other.size);
this.array = resultArray;
this.size += other.size;
return this;
}
float[] result() {
return Arrays.copyOf(array, size);
}
}
return collection.stream().collect(
Collector.of(
FloatArray::new, FloatArray::add,
FloatArray::combine, FloatArray::result));
}
It'd be much simpler to convert your collection directly to a float[]
without streams, either by yourself with a straightforward loop --
float[] result = new float[collection.size()];
int i = 0;
for (Float f : collection) {
result[i++] = f;
}
or with a third-party library, e.g. Guava's Floats.toArray
.