I am trying to convert a double[]
to float[]
using Java 8 lambda calculus. So far, I just created a toy method which should be revised. Trying to find help for converting primitive arrays. Mostly, is there any approach to get rid of the guava conversion because converting to List and back are too heavy for large arrays.
import com.google.common.primitives.Floats;
public static float[] doubleToFloat(double[] vector) {
Float[] f = Arrays.stream(vector).<Float>mapToObj(x -> (float) x).toArray(Float[]::new);
return Floats.toArray(Arrays.asList(f));
}
The lambda expressions can also be used to initialize arrays in Java.
Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
You can have arrays of any of the Java primitives or reference variables. The important point to remember is that when created, primitive arrays will have default values assigned, but object references will all be null.
forEach((e) -> { System. out. print(e + ", "); }); Here, we are passing the lambda expression as an argument to ArrayList forEach().
There is no specialized FloatStream
, so what you want is not doable with the Streams API.
If you want to get the benefits of float
(half the memory of double
) and still use streams, you will have to store your floats encoded in ints:
double[] doubles = new double[]{1.2, 3.5, 4};
int[] floatsAsInts = Arrays.stream(doubles)
.mapToInt(d -> Float.floatToRawIntBits((float) d))
.toArray();
Arrays.stream(floatsAsInts)
.forEach(i -> System.out.println(Float.intBitsToFloat(i)));
You would have to have an overwhelmingly good reason to torture yourself like this. Unless you are planning to store a hundred million numbers in this array, you are likely better off just using double[].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With