Java: Equivalent of Python's range(int, int)? Java: Equivalent of Python's range(int, int)? python python

Java: Equivalent of Python's range(int, int)?


Old question, new answer (for Java 8)

IntStream.range(0, 10).forEach(n -> System.out.println(n));

or with method references:

IntStream.range(0, 10).forEach(System.out::println);


Guava also provides something similar to Python's range:

Range.closed(1, 5).asSet(DiscreteDomains.integers());

You can also implement a fairly simple iterator to do the same sort of thing using Guava's AbstractIterator:

return new AbstractIterator<Integer>() {  int next = getStart();  @Override protected Integer computeNext() {    if (isBeyondEnd(next)) {      return endOfData();    }    Integer result = next;    next = next + getStep();    return result;  }};


I'm working on a little Java utils library called Jools, and it contains a class Range which provides the functionality you need (there's a downloadable JAR).
Constructors are either Range(int stop), Range(int start, int stop), or Range(int start, int stop, int step) (similiar to a for loop) and you can either iterate through it, which used lazy evaluation, or you can use its toList() method to explicitly get the range list.

for (int i : new Range(10)) {...} // i = 0,1,2,3,4,5,6,7,8,9for (int i : new Range(4,10)) {...} // i = 4,5,6,7,8,9for (int i : new Range(0,10,2)) {...} // i = 0,2,4,6,8Range range = new Range(0,10,2);range.toList(); // [0,2,4,6,8]