11

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?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Elad Benda
  • 35,076
  • 87
  • 265
  • 471

2 Answers2

29

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.

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • 1
    how will you do the same from short[] to Int[] ? – Elad Benda Jun 17 '16 at 13:40
  • @EladBenda There is no `ShortStream` in the stream API, so you wouldn't use it for that task. You can use a traditional for loop though. – Tunaki Jun 17 '16 at 13:43
  • 5
    The `.mapToLong(i -> i)` step is obsolete as the conversion from `int` to `long` can be handled intrinsically: `Arrays.stream(intArray).asLongStream().toArray()`… – Holger Jun 17 '16 at 15:12
  • @Holger I think I never noticed that method. Thanks! – Tunaki Jun 17 '16 at 15:16
  • The key thing is avoiding boxing of the primitive types. So, probably asLongStream is a bit better because it avoids doing a lot of boxing/unboxing for the map call. – Jilles van Gurp Jun 17 '16 at 15:42
  • 2
    @JillesvanGurp There won't be any boxing with `mapToLong`, the mapper accepts an `int` and returns a `long`, keeping primitive types. Reading the code `asLongStream()` is only short-hand for `mapToLong(i -> i)`, but it makes it a bit clearer and avoids creating a lambda. – Tunaki Jun 17 '16 at 15:53
4

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));
T. Neidhart
  • 6,060
  • 2
  • 15
  • 38