Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
startInclusiveintThe first number.
endExclusiveintThe 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]
15

Indexes 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. Ivan

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.