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

- 62,466
- 11
- 102
- 153

- 119,074
- 188
- 476
- 699
-
1Do you mean a Python 2.x range which returns a list, or a Python 3.x range which returns an iterator (equivalent to the 2.x xrange)? The former is relatively simple to implement as others have done below, but the iterator version is a bit more tricky. – Dave Kirby Sep 24 '10 at 21:13
-
http://stackoverflow.com/questions/16570091/for-loop-like-python-range-function/31867991#31867991 – zengr Aug 19 '15 at 23:32
-
For a range of any `Comparable` s see [this](https://stackoverflow.com/a/50245738/3992939) answer – c0der May 09 '18 at 04:55
-
For a range with stepping see [this](https://stackoverflow.com/questions/58052429/python-like-range-with-stepping-in-pure-java/58058221) – Sławomir Lenart Sep 23 '19 at 10:08
14 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);

- 8,989
- 7
- 48
- 78

- 3,065
- 2
- 17
- 9
-
1
-
6
-
https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html – jhodges Aug 17 '16 at 19:34
-
1the first example could just be: `Intstream.range(0,10).forEach( n -> System.out.println(n)); ` – Marko Nov 26 '20 at 11:03
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;
}
};

- 11,558
- 4
- 45
- 67
-
6I wish I had seen this before I implemented my own generic range. It's nice but still another reminder of how clunky Java can be compared to more functional languages. – z7sg Ѫ Nov 27 '12 at 19:09
-
14`Range#asSet` is seems to have become deprecated. You now need to do this: `ContiguousSet.create(Range.closed(low, high), DiscreteDomain.integers())` – Chthonic Project Dec 26 '13 at 22:50
-
-
1From Java 8, IntStream and LongStream have methods range and rangeClosed. – Jose Manuel Gomez Alvarez Dec 19 '18 at 22:51
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]

- 76,817
- 74
- 166
- 248
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());

- 993
- 13
- 12
You can use the following code snippet in order to get a range set of integers:
Set<Integer> iset = IntStream.rangeClosed(1, 5).boxed().collect
(Collectors.toSet());

- 1,694
- 22
- 29
public int[] range(int start, int stop)
{
int[] result = new int[stop-start];
for(int i=0;i<stop-start;i++)
result[i] = start+i;
return result;
}
Forgive any syntax or style errors; I normally program in C#.

- 70,210
- 21
- 112
- 164
-
given that Vivien Barousse beat you to an answer, why don't you delete yours to avoid any dup. Unless you really plan to nicely flesh it out of course. – aaronasterling Sep 24 '10 at 19:24
-
9They're similar; I think mine's a little more readable. His use of "length" is misleading, and I don't think his meets the Python spec (he includes the upper bound, which http://www.network-theory.co.uk/docs/pytut/rangeFunction.html says doesn't happen in Python). If you think one's a dupe, I believe you have sufficient reputation to deal with it yourself. – KeithS Sep 24 '10 at 20:06
public int[] range(int start, int length) {
int[] range = new int[length - start + 1];
for (int i = start; i <= length; i++) {
range[i - start] = i;
}
return range;
}
(Long answer just to say "No")

- 20,555
- 2
- 63
- 64
-
Also, see that "range" in python 3 and the preferred "xrange" in Python 2 return a "live" object that does not use up memory for each item it contains. That would be even bigger to implement in Java. – jsbueno Sep 25 '10 at 00:58
Java 9 - IntStream::iterate
Since Java 9 you can use IntStream::iterate
and you can even customize the step. For example if you want int
array :
public static int[] getInRange(final int min, final int max, final int step) {
return IntStream.iterate(min, i -> i < max, i -> i + step)
.toArray();
}
or List
:
public static List<Integer> getInRange(final int min, final int max, final int step) {
return IntStream.iterate(min, i -> i < max, i -> i + step)
.boxed()
.collect(Collectors.toList());
}
And then use it :
int[] range = getInRange(0, 10, 1);

- 1
- 1

- 15,659
- 4
- 36
- 63
IntStream.range(0, 10).boxed().collect(Collectors.toUnmodifiableList());

- 31
- 1
- 4
-
1It would help if you explained *how* this code solves the problem. – Robert Columbia Oct 23 '19 at 14:01
Groovy's nifty Range class can be used from Java, though it's certainly not as groovy.

- 1,322
- 14
- 26
The "Functional Java" library allows to program in such a way to a limited degree, it has a range() method creating an fj.data.Array instance.
See:
Similarly the "Totally Lazy" library offers a lazy range method: http://code.google.com/p/totallylazy/

- 10,222
- 7
- 53
- 80
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

- 167
- 1
- 2
- 14
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.

- 6,260
- 1
- 28
- 23
-
5You don't usually use it for a loop in python either. There's almost always a cleaner way to iterate. – Daenyth Sep 24 '10 at 19:16
-
Well, range is usually used in a for loop. But for loops are often used without range. – FogleBird Sep 24 '10 at 20:14
Java 8
private static int[] range(int start, int stop, int step) {
int[] result = new int[(stop-start)%step == 0 ? (stop-start)/step : (stop-start)/step+1];
int count = 0;
Function<Integer, Boolean> condition = step > 0 ? (x) -> x < stop : (x) -> x > stop;
for (int i = start; condition.apply(i); i += step) {
result[count] = i;
count++;
}
return result;
}

- 11
- 2
-
Welcome to StackOverflow. While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit](https://stackoverflow.com/posts/65020704/edit) your answer to add explanations and give an indication of what limitations and assumptions apply. – Ruli Nov 26 '20 at 11:48