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

Question:

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

Asked By: Nick Heiner

||

Answers:

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”)

Answered By: Vivien Barousse
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#.

Answered By: KeithS

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.

Answered By: Nikki9696

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]
Answered By: Amir Rachum

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;
  }
};
Answered By: Simon Steele

Groovy’s nifty Range class can be used from Java, though it’s certainly not as groovy.

Answered By: John

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());
Answered By: jiehanzheng

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/

Answered By: tkruse

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);
Answered By: jhodges

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());
Answered By: Julian

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);
Answered By: Michał Krzywański
IntStream.range(0, 10).boxed().collect(Collectors.toUnmodifiableList());
Answered By: pchopinet

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

Answered By: HDubz

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;
}
Answered By: Sergey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.