为了账号安全,请及时绑定邮箱和手机立即绑定

类似于 Python 的范围,在纯 Java 中步进

类似于 Python 的范围,在纯 Java 中步进

qq_花开花谢_0 2023-08-16 18:00:50
In [1]: range(-100, 100, 20) Out[1]: [-100, -80, -60, -40, -20, 0, 20, 40, 60, 80]Array使用 Java 标准库而不是编写自己的函数来创建像上面这样的最简单方法是什么?有IntStream.range(-100, 100),但步骤被硬编码为 1。这不是 Java 的重复:相当于 Python 的 range(int, int)?,因为我需要step数字之间的(偏移量)并且想要使用 java 内置库而不是第 3 方库。在添加我自己的问题和答案之前,我已经检查了该问题和答案。差异很微妙但很重要。
查看完整描述

4 回答

?
阿晨1998

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();

}

查看完整回答
反对 回复 2023-08-16
?
四季花海

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();
}


查看完整回答
反对 回复 2023-08-16
?
宝慕林4294392

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());

上面的代码可以更改为(使用IntStreamStream

List<Integer> collect = Stream.iterate(-100, v -> v < 100, v -> v + 20)
    .collect(Collectors.toList());


查看完整回答
反对 回复 2023-08-16
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

最好只迭代必要的序列。

IntStream.range(-100 / 20, 100 / 20).map(i -> i * 20); // only iterate [-5, 5] items


查看完整回答
反对 回复 2023-08-16
  • 4 回答
  • 0 关注
  • 132 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信