[英]In Java what's the fastest and easiest way to convert an array of String into an array of float?
I have something like this : 我有这样的事情:
String text[]="5.75,9.05,8.16,0.94,-0.10,-0.56,3.60".split(",");
And now I'm doing this to convert it to an array of float : 现在,我正在执行此操作以将其转换为float数组:
float f[]=new float[text.length];
for (int i=0;i<f.length;i++)
f[i]=Float.parseFloat(text[i]);
I wonder if there is a one liner to do something like this : 我想知道是否有一个班轮做这样的事情:
float f[]=(float)text[]
? float f[]=(float)text[]
吗?
In Java 8
在Java 8
Code : 代码 :
String text = "5.75,9.05,8.16,0.94,-0.10,-0.56,3.60 ";
String[] spText = text.split(",");
List<Float> list = Stream.of(spText)
.map(f -> Float.parseFloat(f))
.collect(Collectors.toList());
list.forEach(f -> System.out.print(" " + f));
Output : 输出 :
5.75 9.05 8.16 0.94 -0.1 -0.56 3.6
Explanation : 说明 :
Stream class accept a array and you parse all String to float type one by one and you collect them in to a list which has type Float and print them out 流类接受一个数组,然后将所有String解析为一个浮点类型,然后将它们收集到一个类型为Float的列表中并打印出来
One issue : 一个问题 :
a String can be converted to an array of type String. 字符串可以转换为字符串类型的数组。
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: java.lang.String cannot be converted to java.lang.String[] 线程“主”中的异常java.lang.RuntimeException:无法编译的源代码- 不兼容的类型:java.lang.String无法转换为java.lang.String []
Unless you're using Java 8, this is the fastest and easiest way to do what you need. 除非您使用的是Java 8,否则这是执行所需操作的最快,最简单的方法。
If you're using Java 8, you can do the following one liner: 如果您使用的是Java 8,则可以执行以下一种操作:
Float f[] = Arrays.stream(text).map(t -> Float.parseFloat(t)).toArray(Float[]::new);
在Java 8中,您应该能够执行以下操作:
float f[] = Arrays.stream(text).map(Float::parseFloat).toArray(Float[]::new);
First things first: while it is legal to declare an array using brackets after the variable's name, it is not recommended to do so. 首先,首先要注意的是:虽然在变量名称后使用方括号声明数组是合法的,但不建议这样做。 The following is the generally accepted way: 以下是公认的方法:
String[] text;
Also, I'm pretty sure you haven't ran your code through a compiler, since your syntax for creating your array isn't correct. 另外,我非常确定您没有通过编译器运行代码,因为创建数组的语法不正确。 The following is one of the correct ways to initialize an array: 以下是初始化数组的正确方法之一:
String[] text = new String[]{"5.75", "9.05", "8.16", "0.94", "-0.10", "-0.56", "3.60"};
Now, to convert your String elements to float use the following: 现在,要将String元素转换为float,请使用以下命令:
String[] text = new String[]{"5.75", "9.05", "8.16", "0.94", "-0.10", "-0.56", "3.60"};
Float[] f = new Float[text.length];
Arrays.stream(text).map(Float::parseFloat).collect(Collectors.toList()).toArray(f);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.