2

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])?

1
  • 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 Commented Dec 23, 2016 at 8:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I guess you could've used float[]::new instead no?
I think valueOf will be more feasible
this will still go through each element of the string array, though its indeed more elegant
Is the Arrays keyword the Java 8 part? That's where my editor is throwing errors.''
@YassinHajaj: see my edit.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.