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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

how will you do the same from short[] to Int[] ?
@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.
The .mapToLong(i -> i) step is obsolete as the conversion from int to long can be handled intrinsically: Arrays.stream(intArray).asLongStream().toArray()
@Holger I think I never noticed that method. Thanks!
@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.
|
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.