到目前为止提出的两种解决方案都不尊重并行化。 @fge 提出的 spliterator 根本不并行。 @RealSkeptic 提出的基于迭代的流将使用缓冲并行化(一些数字将被加载到中间数组中并移交给另一个线程),这并不总是有效。
有一个非常简单的替代解决方案,可以提供正常的并行化(此处end
是独家的):
public static IntStream intRange(int start, int end, int step ) {
int limit = (end-start+step-(step>>31|1))/step;
return IntStream.range(0, limit).map(x -> x * step + start);
}
或者,如果您想考虑非常奇怪的输入,例如intRange(Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE)
:
public static IntStream intRange(int startInclusive, int endExclusive, int step) {
if(step == 0)
throw new IllegalArgumentException("step = 0");
if(step == 1)
return IntStream.range(startInclusive, endExclusive);
if(step == -1) {
// Handled specially as number of elements can exceed Integer.MAX_VALUE
int sum = endExclusive+startInclusive;
return IntStream.range(endExclusive, startInclusive).map(x -> sum - x);
}
if((endExclusive > startInclusive ^ step > 0) || endExclusive == startInclusive)
return IntStream.empty();
int limit = (endExclusive-startInclusive)*Integer.signum(step)-1;
limit = Integer.divideUnsigned(limit, Math.abs(step));
return IntStream.rangeClosed(0, limit).map(x -> x * step + startInclusive);
}