Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda on primitive arrays

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));
}
like image 910
MG. Avatar asked Dec 16 '14 04:12

MG.


People also ask

Can you use lambda expression array?

The lambda expressions can also be used to initialize arrays in Java.

Does Java 8 have lambda?

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.

Can arrays contain primitives?

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.

What is the correct lambda expression to print all the elements of an array?

forEach((e) -> { System. out. print(e + ", "); }); Here, we are passing the lambda expression as an argument to ArrayList forEach().


1 Answers

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

like image 160
Misha Avatar answered Nov 15 '22 18:11

Misha