ric
ric

Reputation: 139

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){
            ret.add(i);
        }

        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?

Upvotes: 2

Views: 8312

Answers (2)

Aaron Davis
Aaron Davis

Reputation: 1731

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

IntStream.range(0, 10)
         .collect(Collectors.toList());

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).

Upvotes: 6

ilya
ilya

Reputation: 1018

If you need a possibility to generate numbers of any type, and you are allowed to use third-party libraries, I would recommend to use Guava Ranges.

Uppermost, Ranges are used to manipulate with ranges, as "mathematical abstractions". But you are allowed to generate sequences from ranges:

Set<Integer> set = ContiguousSet.create(Range.closed(1, 5), DiscreteDomain.integers());
// set contains [2, 3, 4]

By default, Guava supplies you with three kinds of discrete domains: integers, longs and big integers. But you are allowed to create your own:

You can make your own DiscreteDomain objects, but there are several important aspects of the DiscreteDomain contract that you must remember.

Please, consult official docs about DiscreteDomain implementation peculiarities.

Upvotes: 0

Related Questions