Java 8 streams: Convert String[] to Float[] [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 17:17:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!