-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
  • 2,847
  • 7
  • 25
  • 34
dwellman
  • 155
  • 1
  • 8

3 Answers3

9
Arrays.stream(e.getValue()).map(Float::valueOf).toArray(Float[]::new);
Joop Eggen
  • 102,262
  • 7
  • 78
  • 129
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,781
  • 1
  • 8
  • 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
  • 46,817
  • 11
  • 84
  • 103