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

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 Answers1

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.

Community
  • 1
  • 1
JDC
  • 4,247
  • 5
  • 31
  • 74