4 回答
TA貢獻2037條經(jīng)驗 獲得超6個贊
使用IntStream::range應該有效(對于您的特殊步驟20)。
IntStream.range(-100,?100).filter(i?->?i?%?20?==?0);
允許負步驟的一般實現(xiàn)可能如下所示:
/**
?* 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條經(jīng)驗 獲得超5個贊
IntStream::iterate使用種子(自 JDK9 起可用)可以實現(xiàn)相同的效果,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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超5個贊
最好只迭代必要的序列。
IntStream.range(-100 / 20, 100 / 20).map(i -> i * 20); // only iterate [-5, 5] items
添加回答
舉報
