Java For 循环 - 类似 Python 范围函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16570091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For loop - like Python range function
提问by Kacper Lubisz
I was wondering if in Java there is a function like the python range function.
我想知道在 Java 中是否有像 python range 函数这样的函数。
range(4)
and it would return
它会回来
[0,1,2,3]
This was an easy way to make for enhanced loops. It would be great to do this in Java because it would make for loops a lot easier. Is this possible?
这是制作增强循环的简单方法。在 Java 中这样做会很棒,因为它会使 for 循环更容易。这可能吗?
采纳答案by zengr
Java 8 (2014) has added IntStream(similar to apache commons IntRange), so you don't need external lib now.
Java 8 (2014) 添加了IntStream(类似于 apache commons IntRange),因此您现在不需要外部库。
import java.util.stream.IntStream;
IntStream.range(0, 3).forEachOrdered(n -> {
System.out.println(n);
});
forEach
can be used in place of forEachOrdered
too if order is not important.
forEach
forEachOrdered
如果顺序不重要,也可以用来代替。
IntStream.range(0, 3).parallel()
can be used for loops to run in parallel
IntStream.range(0, 3).parallel()
可用于循环并行运行
回答by zw324
Um... for (int i = 0; i < k; i++)
? You don't have to write enhanced for loops all day, you know, although they are cool...
嗯…… for (int i = 0; i < k; i++)
?你不必整天编写增强的 for 循环,你知道,虽然它们很酷......
And just for the sake of argument:
并且只是为了争论:
for (int i : range(k))
char count: 22
for (int i : range(k))
字符数:22
for (int i = 0; i < k; i++)
char count: 27
for (int i = 0; i < k; i++)
字符数:27
Discounting the implementation of range
, it is pseudo even.
打折 的实现range
,它是伪偶数。
回答by Henry Keiter
There's no Java equivalent to the range
function, but there is an enhanced for-loop:
没有与该range
函数等效的 Java ,但有一个增强的 for-loop:
for (String s : strings) {
// Do stuff
}
You could also roll your own range
function, if you're really attached to the syntax, but it seems a little silly.
range
如果您真的很喜欢语法,您也可以推出自己的函数,但这似乎有点傻。
public static int[] range(int length) {
int[] r = new int[length];
for (int i = 0; i < length; i++) {
r[i] = i;
}
return r;
}
// ...
String s;
for (int i : range(arrayOfStrings.length)) {
s = arrayOfStrings[i];
// Do stuff
}
回答by óscar López
If you really, really want to obtain an equivalent result in Java, you'll have to do some more work:
如果你真的,真的想在 Java 中获得等效的结果,你将不得不做更多的工作:
public int[] range(int start, int end, int step) {
int n = (int) Math.ceil((end-start)/(double)step);
int[] arange = new int[n];
for (int i = 0; i < n; i++)
arange[i] = i*step+start;
return arange;
}
Now range(0, 4, 1)
will return the expected value, just like Python: [0, 1, 2, 3]
. Sadly there isn't a simpler way in Java, it's nota very expressive language, like Python.
现在range(0, 4, 1)
将返回预期值,就像 Python: 一样[0, 1, 2, 3]
。遗憾的是,Java 中没有更简单的方法,它不是一种非常有表现力的语言,如 Python。
回答by Subhrajyoti Majumder
Its not available that true. But you make a static method and use it -
它不是真的。但是你创建了一个静态方法并使用它 -
public static int[] range(int index){
int[] arr = new int[index];
for(int i=0;i<index;i++){
arr[i]=i;
}
return arr;
}
回答by Zutty
Use Apache Commons Lang:
new IntRange(0, 3).toArray();
I wouldn't normally advocate introducing external libraries for something so simple, but Apache Commons are so widely used that you probably already have it in your project!
我通常不提倡为这么简单的事情引入外部库,但是 Apache Commons 的使用非常广泛,以至于您可能已经在您的项目中使用了它!
Edit: I know its not necessarily as simple or fast as a for loop, but its a nice bit of syntactic sugar that makes the intent clear.
编辑:我知道它不一定像 for 循环那样简单或快速,但它的一些语法糖可以使意图清晰。
Edit: See @zengr's answerusing IntStream
in Java 8 .
编辑:见@zengr's answerusing IntStream
in Java 8 。
回答by Barranka
As far as I know, there's not an equivalent function in java. But you can write it yourself:
据我所知,java 中没有等效的函数。但是你可以自己写:
public static int[] range(int n) {
int[] ans = new int[n];
int i;
for(i = 0; i < n; i++) {
ans[i] = i;
}
return ans;
}
回答by jlordo
Without an external library, you can do the following. It will consume significantly less memory for big ranges than the current accepted answer, as there is no array created.
如果没有外部库,您可以执行以下操作。与当前接受的答案相比,它在大范围内消耗的内存要少得多,因为没有创建数组。
Have a class like this:
有一个这样的类:
class Range implements Iterable<Integer> {
private int limit;
public Range(int limit) {
this.limit = limit;
}
@Override
public Iterator<Integer> iterator() {
final int max = limit;
return new Iterator<Integer>() {
private int current = 0;
@Override
public boolean hasNext() {
return current < max;
}
@Override
public Integer next() {
if (hasNext()) {
return current++;
} else {
throw new NoSuchElementException("Range reached the end");
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("Can't remove values from a Range");
}
};
}
}
and you can simply use it like this:
你可以像这样简单地使用它:
for (int i : new Range(5)) {
System.out.println(i);
}
you can even reuse it:
你甚至可以重复使用它:
Range range5 = new Range(5);
for (int i : range5) {
System.out.println(i);
}
for (int i : range5) {
System.out.println(i);
}
As Henry Keiterpointed out in the comment below, we could add following method to the Range
class (or anywhere else):
正如Henry Keiter在下面的评论中指出的那样,我们可以将以下方法添加到Range
类(或其他任何地方):
public static Range range(int max) {
return new Range(max);
}
and then, in the other classes we can
然后,在其他类中,我们可以
import static package.name.Range.range;
and simply call
并简单地调用
for (int i : range(5)) {
System.out.println(i);
}