Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

python

Does Java have an equivalent to Python's range(int, int) method?

like image 492
Nick Heiner Avatar asked Sep 24 '10 19:09

Nick Heiner


People also ask

Does Java have ranges?

The range() method in the IntStream class in Java is used to return a sequential ordered IntStream from startInclusive to endExclusive by an incremental step of 1.


2 Answers

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); 
like image 73
jhodges Avatar answered Oct 28 '22 01:10

jhodges


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;   } }; 
like image 38
Simon Steele Avatar answered Oct 28 '22 01:10

Simon Steele