在java中将字符串数组转换为浮点数组 [英] Converting an array of strings to an array of floats in java
问题描述
我正在尝试将字符串数组转换为Java中的浮点数组,是否有更优雅的方法来执行此操作,而不是使用循环遍历字符串数组的每个元素并使用类似的方式将其转换为浮点数 Float.parseFloat(strings [i])
?
I am trying to convert an array of strings to an array of floats in Java, is there a more elegant way to do this than going through each element of the string array with a loop and converting it to a float using something like Float.parseFloat(strings[i])
?
推荐答案
我做不知道这是否真的更好,但使用Java 8你可以通过以下方式转换数组:
I do not know if this is really better, but using Java 8 you could convert the array the following way:
String[] strings = new String[] {"1", "2", "3", "4"};
Float[] floats = Arrays.stream(strings).map(Float::valueOf).toArray(Float[]::new);
如果你想使用 double
而不是你可以使用原始类型(不幸的是,蒸汽不提供类似 mapToFloat
或 FLoatStream
class,请参阅此处了解详情):
If you want to use double
instead you could use the primitive type (unfortunately the steams do not provide something like mapToFloat
or a FLoatStream
class, see here for details):
double[] doubles = Arrays.stream(strings).mapToDouble(Double::parseDouble).toArray();
备注:
请注意使用 parseDouble
与 valueOf
的区别:
parseDouble
返回基元类型,而 valuOf
将返回盒装类型。
Please notice also the difference of using parseDouble
versus valueOf
:
parseDouble
returns the primitive type, whereas valuOf
will return the boxed type.
这篇关于在java中将字符串数组转换为浮点数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!