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])
?
Asked
Active
Viewed 9,030 times
2

Ethan Jones
- 21
- 1
- 3
-
I guess you have iterate through each element of the array. And at the time using Float.parseFloat check if the element is of type Float using instanceof keyword – Chinmay Dec 23 '16 at 08:37
1 Answers
5
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);
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();
Remark:
Please notice also the difference of using parseDouble
versus valueOf
:
parseDouble
returns the primitive type, whereas valuOf
will return the boxed type.
-
-
-
this will still go through each element of the string array, though its indeed more elegant – xro7 Dec 23 '16 at 08:40
-
Is the `Arrays` keyword the Java 8 part? That's where my editor is throwing errors.'' – Ethan Jones Dec 23 '16 at 08:42
-
-
-
@EthanJones: it is part of the Java SDK: `java.util.Arrays`. Be sure to have the appropriate import statement on top. – JDC Dec 23 '16 at 08:48