-1

I have an array String[] and I'd like to convert to array Float[]

Consider e is a String[] supplied via HttpServletRequest::getParameterMap(). I tried:

Arrays.stream(e.getValue()).mapToDouble(Float::parseFloat).boxed().toArray(Float[]::new));

Got exception:

java.lang.ArrayStoreException: java.lang.Double

So then I tried:

Arrays.stream(e.getValue()).mapToDouble(Double::parseDouble).boxed().toArray(Float[]::new));

Same result.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
dwellman
  • 175
  • 2
  • 8

3 Answers3

9
Arrays.stream(e.getValue()).map(Float::valueOf).toArray(Float[]::new);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

You could try this to generate a Float[] array:

Arrays.stream(e.getValue()).map(Float::valueOf).toArray(Float[]::new);

You have to handle possible NumberFormatException.

Unfortunately, there is no class FloatStream for primitive float, but since you want to get an Float[] anyway, the code above is just fine.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25
0

You are still generating a Float[] array in your second test.

For a Double[] result, use:

Arrays
    .stream(e.getValue())
    .mapToDouble(Double::parseDouble)
    .boxed()
    .toArray(Double[]::new);

For a Float[] result (no need for boxed in this case), use:

Arrays
    .stream(e.getValue())
    .map(Float::parseFloat)
    .toArray(Float[]::new);
Mena
  • 47,782
  • 11
  • 87
  • 106