There is a minor error in your code, which we will fix first to reveal the larger problem at hand:
float[] data = input.map(x -> Float.parseFloat(x)).toArray(size -> new float[]);
should be:
float[] data = input.map(x -> Float.parseFloat(x)).toArray(size -> new float[size]);
^this is new
Even if it might not seem like it, your question is realted to generics. Let us take a look at the definition of Stream#toArray(...)
:
public <A> A[] toArray(IntFunction<A[]> generator)
Since this method is generic in A
, the type A
must not be a primitive. You, on the other hand, try to set A
to float
(this is done through type inference, this is why you do not see the generic parameters in your code). The compiler now complains that:
error: incompatible types: inference variable A has incompatible bounds
float[] data = input.stream().map(x -> Float.parseFloat(x)).toArray(size -> new float[size]);
^
equality constraints: float
upper bounds: Object
where A is a type-variable:
A extends Object declared in method <A>toArray(IntFunction<A[]>)
1 error
This question and its answer provide solutions/workarounds to the problem of converting a String
-stream to a float[]
.