像Python一样的范围,可踏入纯Java

Sła*_*art 1 java range

In [1]: range(-100, 100, 20)
Out[1]: [-100, -80, -60, -40, -20, 0, 20, 40, 60, 80]
Run Code Online (Sandbox Code Playgroud)

Array使用Java标准库而不是编写自己的函数,最简单的创建方法是什么?

IntStream.range(-100, 100),但步骤已硬编码为1。


这不是Java的重复:是否等效于Python的range(int,int)?,因为我需要step在数字之间添加一个(offset),并希望使用Java内置库而不是第三方库。在添加我自己的内容之前,我已经检查了该问题和答案。差异是微妙的但必不可少的。

小智 7

使用IntStream::range应该可以工作(用于的特殊步骤20)。

IntStream.range(-100, 100).filter(i -> i % 20 == 0);
Run Code Online (Sandbox Code Playgroud)

允许采取负面措施的一般实现如下所示:

/**
 * 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();
}
Run Code Online (Sandbox Code Playgroud)

有关详细版本,请参见https://gist.github.com/lutzhorn/9338f3c43b249a618285ccb2028cc4b5


mic*_*alk 5

IntStream::iterate(从JDK9开始可用)可以取得相同的效果,它需要种子,IntPredicate并且IntUnaryOperator。通过使用辅助方法,它看起来像:

public static int[] getInRange(int min, int max, int step) {
        return IntStream.iterate(min, operand -> operand < max, operand -> operand + step)
                .toArray();
}
Run Code Online (Sandbox Code Playgroud)