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.
IntStream.range(0, 5); // 0, 1, 2, 3, 4 IntStream.rangeClosed(1, 5); // 1, 2, 3, 4, 5
Try it
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.
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
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)orIntStream.iterate(). - Size is known:
count()andtoArray()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 forArrayList, but O(n) per call forLinkedList. - Boxing: call
boxed()ormapToObj()to get objects;collect(Collectors.toList())does not work on anIntStreamdirectly. - Overflow:
rangeClosed(a, Integer.MAX_VALUE)works correctly, unlike a naivefor (int i = a; i <= MAX; i++), which never ends. - Prefer a loop when mutating: use
rangeto build values; a plainforis clearer for side effects.