Does Java have an equivalent to Python\'s range(int, int)
method?
If you mean to use it like you would in a Python loop, Java loops nicely with the for statement, which renders this structure unnecessary for that purpose.
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,9
for (int i : new Range(4,10)) {...} // i = 4,5,6,7,8,9
for (int i : new Range(0,10,2)) {...} // i = 0,2,4,6,8
Range range = new Range(0,10,2);
range.toList(); // [0,2,4,6,8]
IntStream.range(0, 10).boxed().collect(Collectors.toUnmodifiableList());
I know this is an old post but if you are looking for a solution that returns an object stream and don't want to or can't use any additional dependencies:
Stream.iterate(start, n -> n + 1).limit(stop);
start - inclusive stop - exclusive
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);
Since Guava 15.0, Range.asSet() has been deprecated and is scheduled to be removed in version 16. Use the following instead:
ContiguousSet.create(Range.closed(1, 5), DiscreteDomain.integers());