How to create a sequence of numbers
Short answer
IntStream.range(a, b) gives the numbers from a up to b exclusive, rangeClosed() inclusive:
void main() {
IO.println(IntStream.range(1, 5).boxed().toList());
IO.println(IntStream.rangeClosed(1, 5).boxed().toList());
}Output:
[1, 2, 3, 4]
[1, 2, 3, 4, 5]With a step
iterate() with a condition works like a for loop:
void main() {
IO.println(IntStream.iterate(0, n -> n <= 20, n -> n + 5).boxed().toList());
IO.println(IntStream.iterate(10, n -> n > 0, n -> n - 3).boxed().toList());
}Output:
[0, 5, 10, 15, 20]
[10, 7, 4, 1]Instead of a loop
A range often replaces a counting loop:
void main() {
int sumOfSquares = IntStream.rangeClosed(1, 10).map(n -> n * n).sum();
IO.println(sumOfSquares);
}Output:
385An infinite stream
iterate() without a condition and generate() are infinite — limit them with limit():
void main() {
IO.println(Stream.iterate(1, n -> n * 2).limit(8).toList());
IO.println(Stream.generate(() -> "ab").limit(3).collect(Collectors.joining()));
}Output:
[1, 2, 4, 8, 16, 32, 64, 128]
abababCommon mistake
Forgetting boxed() before toList(). IntStream has no toList() method, because a list cannot hold int values:
void main() {
var numbers = IntStream.range(0, 3).toList();
}Output:
Main.java:2: error: cannot find symbolFunctions used in this recipe
- IntStream.range() — Creates a stream of integers from a range.
- Stream.iterate() — Creates a stream where each element is computed from the previous one.
- Stream.generate() — Creates an infinite stream from the values of a supplier function.