使用纯 Java 步进的 Python 类范围 [英] Python like range with stepping in pure Java
问题描述
In [1]: range(-100, 100, 20)
Out[1]: [-100, -80, -60, -40, -20, 0, 20, 40, 60, 80]
使用 Java 的标准库而不是编写自己的函数来创建上述 Array
的最简单方法是什么?
What's the easiest way to create Array
like above using standard libraries of Java instead of writting own function?
有IntStream.range(-100, 100)
,但是step被硬编码为1.
There is IntStream.range(-100, 100)
, but step is hardcoded to 1.
这不是 Java:等效的重复Python 的 range(int, int)?,因为我需要在数字之间有一个 step
(偏移量),并且想要使用 java 内置库而不是 3rd 方库.在添加我自己的问题和答案之前,我已经检查了该问题和答案.差异很微妙,但很重要.
THIS IS NOT A DUPLICATE of Java: Equivalent of Python's range(int, int)?, because I need a step
(offset) between numbers and want to use java built-in libraries instead of 3rd-party libraries. I've checked that question and answers before adding my own. The difference is subtle but essential.
推荐答案
使用 IntStream::range
应该可以工作(对于 20 的特殊步骤
).
IntStream.range(-100, 100).filter(i -> i % 20 == 0);
允许负面步骤的一般实现可能如下所示:
A general implementation allowing negative steps could look like this:
/**
* 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();
}
参见https://gist.github.com/lutzhorn/9338f3c43b249a6180285cc4b249a6180285版本.
See https://gist.github.com/lutzhorn/9338f3c43b249a618285ccb2028cc4b5 for a detailed version.
这篇关于使用纯 Java 步进的 Python 类范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!