Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an int array to long array using Java 8?

I have tried few ways unsuccessfully.

this.tileUpdateTimes is long[] and other.tileUpdateTimes is int[]

this.tileUpdateTimes = Arrays.stream(other.tileUpdateTimes).toArray(size -> new long[size]);
this.tileUpdateTimes = Arrays.stream(other.tileUpdateTimes)
            .map(item -> ((long) item)).toArray();

How can I fix this?

like image 537
Elad Benda Avatar asked Jun 17 '16 13:06

Elad Benda


2 Answers

You need to use the mapToLong operation.

int[] intArray = {1, 2, 3};
long[] longArray = Arrays.stream(intArray).mapToLong(i -> i).toArray();

or, as Holger points out, in this case, you can directly use asLongStream():

int[] intArray = {1, 2, 3};
long[] longArray = Arrays.stream(intArray).asLongStream().toArray();

The map method on primitive streams return a stream of the same primitive type. In this case, IntStream.map will still return an IntStream.

The cast to long with

.map(item -> ((long) item))

will actually make the code not compile since the mapper used in IntStream.map is expected to return an int and you need an explicit cast to convert from the new casted long to int.

With .mapToLong(i -> i), which expects a mapper returning a long, the int i value is promoted to long automatically, so you don't need a cast.

like image 154
Tunaki Avatar answered Sep 23 '22 03:09

Tunaki


This snippet compiles fine for me and returns the expected result:

    int[] iarr = new int[] { 1, 2, 3, 4, 5, 6 };
    long[] larr = Arrays.stream(iarr)
                        .mapToLong((i) -> (long) i)
                        .toArray();
    System.out.println(Arrays.toString(larr));
like image 40
T. Neidhart Avatar answered Sep 22 '22 03:09

T. Neidhart