问题描述
我尝试了几种失败的方法.
I have tried few ways unsuccessfully.
this.tileUpdateTimes
是long[]
和other.tileUpdateTimes
是int[]
this.tileUpdateTimes = Arrays.stream(other.tileUpdateTimes).toArray(size -> new long[size]);
this.tileUpdateTimes = Arrays.stream(other.tileUpdateTimes)
.map(item -> ((long) item)).toArray();
我该如何解决?
推荐答案
您需要使用 mapToLong
操作.
You need to use the mapToLong
operation.
int[] intArray = {1, 2, 3};
long[] longArray = Arrays.stream(intArray).mapToLong(i -> i).toArray();
或 Holger 指出,在这种情况下,您可以直接使用 asLongStream()
:
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();
原始流上的map
方法返回相同原始类型的流.在这种情况下, IntStream.map
仍会返回IntStream
.
The map
method on primitive streams return a stream of the same primitive type. In this case, IntStream.map
will still return an IntStream
.
使用
.map(item -> ((long) item))
实际上将使代码无法编译,因为预计IntStream.map
中使用的映射器将返回int
和.
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
.
使用.mapToLong(i -> i)
(期望映射器返回long
),int i
值自动升级到long
,因此您不需要强制转换.
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.
这篇关于使用Java 8将int数组转换为long数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!