使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:54:40  来源:igfitidea点击:

Convert an int array to long array using Java 8?

javalambdajava-8java-stream

提问by Elad Benda

I have tried few ways unsuccessfully.

我尝试了几种方法都不成功。

this.tileUpdateTimesis long[]and other.tileUpdateTimesis int[]

this.tileUpdateTimeslong[]并且other.tileUpdateTimesint[]

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 mapToLongoperation.

您需要使用该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 mapmethod on primitive streams return a stream of the same primitive type. In this case, IntStream.mapwill still return an IntStream.

map原始流上的方法返回相同原始类型的流。在这种情况下,IntStream.map仍然会返回一个IntStream.

The cast to longwith

演员阵容long

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

will actually make the code not compile since the mapper used in IntStream.mapis expected to return an intand you need an explicit cast to convert from the new casted longto int.

实际上会使代码无法编译,因为 中使用的映射器IntStream.map预计会返回 anint并且您需要显式转换long才能从新转换为int.

With .mapToLong(i -> i), which expects a mapper returning a long, the int ivalue is promotedto longautomatically, so you don't need a cast.

使用.mapToLong(i -> i),它期望映射器返回 a long,该int ilong自动提升为,因此您不需要强制转换。

回答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));