使用流生成short []

Gil*_*ili 8 java java-8 java-stream

使用连续的短裤范围填充列表的基础上,我尝试生成一组原始短裤.事实证明这比预期的要难得多.

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
Run Code Online (Sandbox Code Playgroud)

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

  1. 原始Stream API不提供shorts 的实现.
  2. 非原始Stream API似乎不提供返回基本数组的机制.

有任何想法吗?

Tag*_*eev 2

您可以考虑使用我的StreamEx库。它通过附加方法扩展了标准流。我的库的目标之一是与旧代码更好的互操作。特别是它有IntStreamEx.toShortArray()IntStreamEx.of(short...)

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

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

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