使用 Java 8 将 int 数组转换为 long 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37882512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert an int array to long array using Java 8?
提问by Elad Benda
I have tried few ways unsuccessfully.
我尝试了几种方法都不成功。
this.tileUpdateTimes
is long[]
and other.tileUpdateTimes
is int[]
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();
How can I fix this?
我怎样才能解决这个问题?
回答by Tunaki
You need to use the mapToLong
operation.
您需要使用该mapToLong
操作。
int[] intArray = {1, 2, 3};
long[] longArray = Arrays.stream(intArray).mapToLong(i -> i).toArray();
or, as Holgerpoints out, in this case, you can directly use asLongStream()
:
或者,正如Holger指出的那样,在这种情况下,您可以直接使用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
.
map
原始流上的方法返回相同原始类型的流。在这种情况下,IntStream.map
仍然会返回一个IntStream
.
The cast to long
with
演员阵容long
与
.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
.
实际上会使代码无法编译,因为 中使用的映射器IntStream.map
预计会返回 anint
并且您需要显式转换long
才能从新转换为int
.
With .mapToLong(i -> i)
, which expects a mapper returning a long
, the int i
value is promotedto long
automatically, so you don't need a cast.
使用.mapToLong(i -> i)
,它期望映射器返回 a long
,该int i
值会long
自动提升为,因此您不需要强制转换。
回答by T. Neidhart
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));