Does Java have an equivalent to Python's range(int, int)
method?
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.
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; } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With