将数组中的流作为int []而不是Integer []返回[duplicate]

问题描述 投票:2回答:2

我有这个数组:

  Integer[] originalItems = itemsArray.stream()
                .distinct()
                .sorted()
                .toArray(Integer[]::new);

我想将其返回为int[]而不是Integer[]

我曾尝试致电.toArray(int[]::new),但出现此错误:不存在类型变量A的实例,因此int []符合A []

java arrays stream integer
2个回答
4
投票
.mapToInt(Integer::intValue).toArray();

代替

.toArray(Integer[]::new);

因为

<A> A[] toArray(IntFunction<A[]> generator);

不适用于基本类型。


0
投票
您有Stream<Integer>个对象流。您可以将其转换为通过IntStream处理原始intmapToInt(i->i),然后在该流上调用toArray()方法,该方法返回int[]
© www.soinside.com 2019 - 2024. All rights reserved.