我想获取一系列值,例如 Python 中的范围函数。
# Python range
a = range(0,1.0,0.01)
b = range(5,10,2)
在Java中,希望得到List这样的结果。
// Java range
public class range{
private double start;
private double end;
private double step;
public range(double start,double end, double step) {
this.start = start;
this.end = end;
this.step = step;
}
public List<Double> asList(){
List<Double> ret = new ArrayList<Double>();
for(double i = this.start;i <= this.end; i += this.step){
ret.add(i);
}
return ret;
}
}
但是,我认为这段代码在需要一定范围的整数时具有计算冗余。
您能否在 Java 中使用更智能的方法或实现?
最佳答案
您可以使用流生成范围并将其收集到列表中
IntStream.range(0, 10)
.collect(Collectors.toList());
请注意,第一个数字包含在内,第二个数字不包含在内。您可以使用 rangeClosed 方法来包含第二个参数。 http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#range-int-int-
对于其他原语还有其他类型的流(例如,参见 DoubleStream.iterate)。
关于java - Java 获取一系列值的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42990614/