-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.

1
  • Replace mapToDouble for a DoubleStream of doubles with map for String input parameters for parseFloat. Commented Oct 4, 2017 at 13:10

3 Answers 3

9
Arrays.stream(e.getValue()).map(Float::valueOf).toArray(Float[]::new);
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Duplicates the other answer.
@Ivar Thanks I fixed that.
@lexicore Well, I added some more comments then the answer you're referring to.
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);

2 Comments

The objective is to create Float[], not Double[].
@lexicore oops. Amending.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.