本文介绍了使用Java 8将int数组转换为long数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了几种失败的方法.

I have tried few ways unsuccessfully.

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();

我该如何解决?

推荐答案

您需要使用 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数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:16