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])?
-
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 keywordChinmay– Chinmay2016-12-23 08:37:05 +00:00Commented Dec 23, 2016 at 8:37
Add a comment
|
1 Answer
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.
7 Comments
Yassin Hajaj
I guess you could've used
float[]::new instead no?J-J
I think valueOf will be more feasible
xro7
this will still go through each element of the string array, though its indeed more elegant
Ethan Jones
Is the
Arrays keyword the Java 8 part? That's where my editor is throwing errors.''JDC
@YassinHajaj: see my edit.
|