Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Java IntStream.range() and rangeClosed()

Reference for Java IntStream.range() and rangeClosed(): generate consecutive integers, exclusive and inclusive ends, empty ranges, and loop replacements.

IntStream.range(start, end) produces the consecutive int values from start up to, but not including, end. IntStream.rangeClosed(start, end) includes end. Both give an ordered, sequential, primitive stream with a known size, and both exist for LongStream too.

They are the stream equivalent of a counting for loop and the usual way to start a pipeline that needs indexes.

Java
IntStream.range(0, 5);        // 0, 1, 2, 3, 4
IntStream.rangeClosed(1, 5);  // 1, 2, 3, 4, 5

Try it

Java Exclusive and inclusive ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Indexing a list and building a grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
static IntStream range(int startInclusive, int endExclusive)
static IntStream rangeClosed(int startInclusive, int endInclusive)
Name Description
startInclusive First value.
endExclusive / endInclusive Bound of the sequence.

Returns: an IntStream of the values in ascending order, empty when start >= end (range) or start > end (rangeClosed).

LongStream.range() and rangeClosed() have the same behavior with long values.

Usage notes

  • Never steps down: the step is always +1. For other steps use filter(i -> i % 3 == 0), map(i -> i * 3) or IntStream.iterate().
  • Size is known: count() and toArray() on a plain range are cheap, and the stream splits well for parallel use.
  • Empty is not an error: reversed bounds just give an empty stream.
  • Indexing lists: list.get(i) inside the pipeline is fine for ArrayList, but O(n) per call for LinkedList.
  • Boxing: call boxed() or mapToObj() to get objects; collect(Collectors.toList()) does not work on an IntStream directly.
  • Overflow: rangeClosed(a, Integer.MAX_VALUE) works correctly, unlike a naive for (int i = a; i <= MAX; i++), which never ends.
  • Prefer a loop when mutating: use range to build values; a plain for is clearer for side effects.