Kac*_*isz 22 python java for-loop function
我想知道在Java中是否有类似python范围函数的函数.
range(4)
Run Code Online (Sandbox Code Playgroud)
它会回来的
[0,1,2,3]
Run Code Online (Sandbox Code Playgroud)
这是一种简化的增强循环方法.在Java中执行此操作会很棒,因为它会使循环变得更容易.这可能吗?
zen*_*ngr 37
Java 8添加了IntStream(类似于apache commons IntRange),因此您现在不需要外部lib.
IntStream.range(0, 3).forEachOrdered(n -> {
//work on n here
});
Run Code Online (Sandbox Code Playgroud)
forEach
forEachOrdered
如果订单不重要,也可以代替它.
jlo*_*rdo 17
没有外部库,您可以执行以下操作.对于大范围,它将比当前接受的答案消耗更少的内存,因为没有创建数组.
有一个这样的课:
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");
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样简单地使用它:
for (int i : new Range(5)) {
System.out.println(i);
}
Run Code Online (Sandbox Code Playgroud)
你甚至可以重复使用它:
Range range5 = new Range(5);
for (int i : range5) {
System.out.println(i);
}
for (int i : range5) {
System.out.println(i);
}
Run Code Online (Sandbox Code Playgroud)
正如Henry Keiter在下面的评论中指出的那样,我们可以在Range
类(或其他任何地方)中添加以下方法:
public static Range range(int max) {
return new Range(max);
}
Run Code Online (Sandbox Code Playgroud)
然后,在其他课程中我们可以
import static package.name.Range.range;
Run Code Online (Sandbox Code Playgroud)
并简单地打电话
for (int i : range(5)) {
System.out.println(i);
}
Run Code Online (Sandbox Code Playgroud)
Zut*_*tty 11
new IntRange(0, 3).toArray();
Run Code Online (Sandbox Code Playgroud)
我通常不会主张为这么简单的事情引入外部库,但是Apache Commons被如此广泛地使用,你可能已经在你的项目中拥有它了!
编辑:我知道它不一定像for循环一样简单或快速,但它的一些语法糖使得意图清晰.
编辑:在Java 8中使用@ zengr的答案IntStream
.
zw3*_*324 10
嗯... for (int i = 0; i < k; i++)
?你知道,你不必整天都在编写增强的for循环,尽管它们很酷......
只是为了争论:
for (int i : range(k))
字数:22
for (int i = 0; i < k; i++)
字数:27
折扣执行range
,它是伪甚至.
归档时间: |
|
查看次数: |
38833 次 |
最近记录: |