gpt4 book ai didi

java - 使用流生成 short[]

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:55:38 25 4
gpt4 key购买 nike

基于 Populating a List with a contiguous range of shorts我尝试生成一组原始短裤。事实证明,这比预期的要难得多。

Short[] range = IntStream.range(0, 500).mapToObj(value -> (short) value).toArray(Short[]::new) 有效但是:

short[] range = IntStream.range(0, 500).mapToObj(value -> (short) value).toArray(short[]::new) 生成编译器错误:

method toArray in interface Stream<T> cannot be applied to given types;
required: IntFunction<A[]>
found: short[]::new
reason: inference variable A has incompatible bounds
equality constraints: short
upper bounds: Object
where A,T are type-variables:
A extends Object declared in method <A>toArray(IntFunction<A[]>)
T extends Object declared in interface Stream

这似乎是两个问题的交集:

  1. 原始流 API 不提供 short 的实现。
  2. 非原始 Stream API 似乎没有提供返回原始数组的机制。

有什么想法吗?

最佳答案

您可以考虑使用我的 StreamEx图书馆。它使用额外的方法扩展标准流。我的库的目标之一是更好地与旧代码进行互操作。特别是它有 IntStreamEx.toShortArray()IntStreamEx.of(short...) :

short[] numbers = IntStreamEx.range(500).toShortArray();
short[] evenNumbers = IntStreamEx.of(numbers).map(x -> x*2).toShortArray();

请注意,它仍然是 int 数字流。当调用toShortArray()时,它们会使用(short) 转换操作自动转换为short 类型,因此可能会发生溢出。所以请小心使用。

还有IntStreamEx.toByteArray()IntStreamEx.toCharArray()DoubleStreamEx.toFloatArray()

关于java - 使用流生成 short[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30790665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com