0

double[] is converted to a List<Float>, I thought Streams map operation could convert a double stream to a float stream, but no... it is still double stream. In the following 2 conversions, the first works, as v.floatValue() becomes float type, but (float) v still is double type. Why?

List<Float> collect = Arrays.stream(vec).boxed().map(v -> v.floatValue()).collect(Collectors.toList());

(float)v is still double. Required List<Float>, provided List<Double>

List<Float> collect2 = Arrays.stream(vec).map(v -> (float) v).boxed().collect(Collectors.toList());
Tiina
  • 4,285
  • 7
  • 44
  • 73

1 Answers1

1

The second doesn't work because DoubleStream.map always returns a DoubleStream. Its parameter is a DoubleUnaryOperator, which is a function that takes a double and returns a double.

You happen to be able to pass the lambda v -> (float) v to map because there is an implicit conversion that converts float to double. As a result, v -> (float) v still counts as "a function that takes a double and returns a double". You are essentially saying v -> (double)(float) v.

Note that there is no FloatStream in the standard library (see here for why), so you cannot have a stream of primitive floats as one of your intermediate steps, like what you are trying to do in your second code snippet.

An alternative to your first approach would be to use mapToObj, directly mapping double to Float:

Arrays.stream(vec).mapToObj(v -> (float)v).toList()
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • please also explain why `Arrays.stream(vec).boxed().map(Double::floatValue).collect(Collectors.toList())` is a `List`, since there is no `FloatStream`, why `map(v -> v.floatValue)` is not treated as `map(v -> (double) v.floatValue)`? – Tiina Aug 01 '23 at 05:58
  • @Tiina There is no `FloatStream` for primitive `float`s, but there is `Stream`, and that's what you get from using `.boxed().map(Double::floatValue)`. `boxed` makes `Stream`, and unlike `DoubleStream.map`, `Stream.map` can transform the elements to other reference types. – Sweeper Aug 01 '23 at 06:00
  • @Tiina `Stream` is also the type that `.mapToObj(v -> (float)v)` returns. – Sweeper Aug 01 '23 at 06:01