ric ric -4 years ago 139
Java Question

How to get a range of values in Java

I'd like to get a range of values like range function in Python.

# Python range
a = range(0,1.0,0.01)
b = range(5,10,2)

In Java, I hope to get such result as 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){

return ret;

But, I think this code has calculate redundancy when a range of Integer is needed.

Could you have more smarter way or implementation in Java?

Answer Source

You can use a stream to generate the range and collect it to a list

IntStream.range(0, 10)

Note that the first number is inclusive and the second is exclusive. You can use the rangeClosed method to include the second argument. http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#range-int-int-

There are other types of streams for other primitives (e.g. see DoubleStream.iterate for example).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download