IntStream.range()
Creates a stream of integers from a range.
Available since: Java 8
Syntax
static IntStream range(int startInclusive, int endExclusive)
static IntStream rangeClosed(int startInclusive, int endInclusive)Parameters
| Parameter | Type | Description |
|---|---|---|
| startInclusive | int | The first number. |
| endExclusive | int | The bound: excluded by `range()`, included by `rangeClosed()`. |
Return value
IntStreamA stream of consecutive integers.
Examples
Half-open and closed ranges:
void main() {
IO.println(Arrays.toString(IntStream.range(0, 5).toArray()));
IO.println(IntStream.rangeClosed(1, 5).sum());
}Output:
[0, 1, 2, 3, 4]
15Indexes instead of a for loop:
void main() {
List<String> names = List.of("Anna", "Oleg", "Ivan");
IntStream.range(0, names.size())
.mapToObj(i -> (i + 1) + ". " + names.get(i))
.forEach(IO::println);
}Output:
1. Anna
2. Oleg
3. IvanNotes
IntStream holds primitive int values without boxing and offers sum(), average(), max(). To go back to a stream of objects use boxed() or mapToObj(). For long there is LongStream.range().
See also
- IntStream.sum() — Adds up all numbers of a stream.
- Stream.iterate() — Creates a stream where each element is computed from the previous one.
- Stream.mapToInt() — Turns a stream of objects into a stream of `int` numbers.
Related recipes
In the tutorial
- What a stream is — The Java Stream API — the source, intermediate and terminal operations, creating streams, lazy evaluation and why a stream can be used only once.