问题
I have an array String[]
and I'd like to convert to array Float[]
Consider e
is a String[]
supplied via HttpServletRequest::getParameterMap()
. I tried:
Arrays.stream(e.getValue()).mapToDouble(Float::parseFloat).boxed().toArray(Float[]::new));
Got exception:
java.lang.ArrayStoreException: java.lang.Double
So then I tried:
Arrays.stream(e.getValue()).mapToDouble(Double::parseDouble).boxed().toArray(Float[]::new));
Same result.
回答1:
Arrays.stream(e.getValue()).map(Float::valueOf).toArray(Float[]::new);
回答2:
You could try this to generate a Float[]
array:
Arrays.stream(e.getValue()).map(Float::valueOf).toArray(Float[]::new);
You have to handle possible NumberFormatException
.
Unfortunately, there is no class FloatStream
for primitive float
, but since you want to get an Float[]
anyway, the code above is just fine.
回答3:
You are still generating a Float[]
array in your second test.
For a Double[]
result, use:
Arrays
.stream(e.getValue())
.mapToDouble(Double::parseDouble)
.boxed()
.toArray(Double[]::new);
For a Float[]
result (no need for boxed
in this case), use:
Arrays
.stream(e.getValue())
.map(Float::parseFloat)
.toArray(Float[]::new);
来源:https://stackoverflow.com/questions/46565713/java-8-streams-convert-string-to-float