Stream.iterate() produces an infinite sequential stream in which each element is generated by applying a function (a unary operator) to the previous element. Because the stream is potentially unbounded, you almost always combine it with a terminal operation such as limit().
1. Generating a Sequence of Numbers
This example starts with zero and adds 1 for each subsequent element. We limit the stream to the first 10 elements.
import java.util.stream.Stream;
public class IterateBasicExample {
public static void main(String[] args) {
// Start at 0, with each subsequent element increased by 1.
Stream<Integer> numbers = Stream.iterate(0, n -> n + 1);
// Limit to the first 10 elements and print each number.
numbers.limit(10).forEach(System.out::println);
}
}
Explanation: Here, the initial element is 0. The lambda n -> n + 1 tells the stream to generate the next number by adding one to the current number. Since the stream is infinite, using limit(10) ensures that only 10 numbers are processed.
Output::
0
1
2
3
4
5
6
7
8
9
2 . Generating the Fibonacci Sequence
This example uses Stream.iterate() along with an array to generate pairs representing consecutive Fibonacci numbers. We then map these pairs to extract the first element in each pair (the Fibonacci number).
import java.util.stream.Stream;
public class FibonacciIterate {
public static void main(String[] args) {
// Each element in the stream is an array where:
// - array[0] is the current Fibonacci number,
// - array[1] is the next Fibonacci number.
Stream.iterate(new long[]{0, 1}, pair -> new long[]{pair[1], pair[0] + pair[1]})
.limit(10) // Get the first 10 Fibonacci pairs.
.map(pair -> pair[0]) // Extract the first number from each pair.
.forEach(n -> System.out.print(n + " "));
}
}
Explanation:
We start with the array {0, 1}.
The lambda pair -> new long[]{pair[1], pair[0] + pair[1]} computes the next Fibonacci pair.
We then limit the stream to 10 elements and map each array to its first element. This produces the Fibonacci numbers.
Output::
0 1 1 2 3 5 8 13 21 34