有没有像Enumerable.Range(X,Y)在Java的东西吗? [英] Is there anything like Enumerable.Range(x,y) in Java?
本文介绍了有没有像Enumerable.Range(X,Y)在Java的东西吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么样的C#/。NET的
Is there something like C#/.NET's
IEnumerable<int> range = Enumerable.Range(0, 100); //.NET
在Java中?
in Java?
推荐答案
编辑:从Java 8,这是可能的 java.util.stream.IntStream.range(INT startInclusive,诠释endExclusive)
Edited: As Java 8, this is possible with java.util.stream.IntStream.range(int startInclusive, int endExclusive)
有没有这样的事情在Java中,但你可以有这样的事情:
There is not such thing in Java but you can have something like this:
import java.util.Iterator;
public class Range implements Iterable<Integer> {
private int min;
private int count;
public Range(int min, int count) {
this.min = min;
this.count = count;
}
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int cur = min;
private int count = Range.this.count;
public boolean hasNext() {
return count != 0;
}
public Integer next() {
count--;
return cur++; // first return the cur, then increase it.
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
例如,你可以使用范围通过这种方式:
For example you can use Range by this way:
public class TestRange {
public static void main(String[] args) {
for (int i : new Range(1, 10)) {
System.out.println(i);
}
}
}
另外,如果你不喜欢使用新范围(1,10)
直接,您可以使用工厂类的:
Also if you don't like use new Range(1, 10)
directly, you can use factory class for it:
public final class RangeFactory {
public static Iterable<Integer> range(int a, int b) {
return new Range(a, b);
}
}
这是我厂的测试:
public class TestRangeFactory {
public static void main(String[] args) {
for (int i : RangeFactory.range(1, 10)) {
System.out.println(i);
}
}
}
我希望这将是有益的:)
I hope these will be useful :)
这篇关于有没有像Enumerable.Range(X,Y)在Java的东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文