amaembo / streamex

Enhancing Java Stream API
Apache License 2.0
2.18k stars 249 forks source link

Ability to map Float[] to float[] #258

Closed cowwoc closed 2 years ago

cowwoc commented 2 years ago

Feature request: Ability to map from Float[] to float[] without casting to double along the way.

cowwoc commented 2 years ago

The closest I could find is:

DoubleStreamEx.of(Arrays.stream(boxedFloatArray).mapToDouble(Float::doubleValue)).toFloatArray();

  1. It's not clear whether this casts to double along the way.
  2. The API could be cleaner.

Ideally I'd want to invoke DoubleStreamEx.of(boxedFloatArray).toFloatArray() and/or consider adding FloatStreamEx.

amaembo commented 2 years ago

You can do this simpler:

float[] floats = StreamEx.of(boxedFloatArray).mapToDouble(x -> x).toFloatArray();

Given that float type is not so popular, and there's rarely the necessity to create a Float[] array, I don't think that merging StreamEx.of(boxedFloatArray).mapToDouble(x -> x) into a single call would be really useful for many people. Note that if yuo often deal with Float[], you can always create a utility method like this in your project:

public class StreamUtils {
  public static DoubleStream of(Float[] floats) {
    return StreamEx.of(boxedFloatArray).mapToDouble(x -> x);
  }
}
cowwoc commented 2 years ago

@amaembo float is extremely popular in the machine-learning world where, as far as I'm aware, double is never used.

For what it's worth, I ended up making my own functions:

    /**
     * Unboxes an array of floats.
     *
     * @param array an array of boxed types
     * @return an array of primitive types
     * @throws NullPointerException if {@code array} is null
     */
    public static float[] unbox(Float[] array)
    {
        float[] result = new float[array.length];
        for (int i = 0; i < result.length; ++i)
            result[i] = array[i];
        return result;
    }

    /**
     * Boxes an array of floats.
     *
     * @param array an array of boxed types
     * @return an array of primitive types
     * @throws NullPointerException if {@code array} is null
     */
    public static Float[] box(float[] array)
    {
        Float[] result = new Float[array.length];
        for (int i = 0; i < result.length; ++i)
            result[i] = array[i];
        return result;
    }

It is simple enough, and does not ever cast to double.

amaembo commented 2 years ago

Sure, these transformations are simple enough to write once with loops. This also would be faster and produce less garbage, compared to streams.