4 回答
TA贡献2037条经验 获得超6个赞
使用IntStream::range
应该有效(对于您的特殊步骤20
)。
IntStream.range(-100, 100).filter(i -> i % 20 == 0);
允许负步骤的一般实现可能如下所示:
/**
* Generate a range of {@code Integer}s as a {@code Stream<Integer>} including
* the left border and excluding the right border.
*
* @param fromInclusive left border, included
* @param toExclusive right border, excluded
* @param step the step, can be negative
* @return the range
*/
public static Stream<Integer> rangeStream(int fromInclusive,
int toExclusive, int step) {
// If the step is negative, we generate the stream by reverting all operations.
// For this we use the sign of the step.
int sign = step < 0 ? -1 : 1;
return IntStream.range(sign * fromInclusive, sign * toExclusive)
.filter(i -> (i - sign * fromInclusive) % (sign * step) == 0)
.map(i -> sign * i)
.boxed();
}
TA贡献1811条经验 获得超5个赞
IntStream::iterate
使用种子(自 JDK9 起可用)可以实现相同的效果,IntPredicate
并且IntUnaryOperator
. 使用辅助方法,它看起来像:
public static int[] range(int min, int max, int step) { return IntStream.iterate(min, operand -> operand < max, operand -> operand + step) .toArray(); }
TA贡献2021条经验 获得超8个赞
另一种方式:
List<Integer> collect = Stream.iterate(-100, v -> v + 20).takeWhile(v -> v < 100) .collect(Collectors.toList());
类似版本IntStream
:
List<Integer> collect = IntStream.iterate( -100, v -> v + 20).takeWhile(v -> v < 100) .boxed().collect(Collectors.toList());
上面的代码可以更改为(使用IntStream
或Stream
)
List<Integer> collect = Stream.iterate(-100, v -> v < 100, v -> v + 20) .collect(Collectors.toList());
TA贡献1900条经验 获得超5个赞
最好只迭代必要的序列。
IntStream.range(-100 / 20, 100 / 20).map(i -> i * 20); // only iterate [-5, 5] items
添加回答
举报