Generate Sequences Using Stream.iterate() in Java
Problem
Stream.iterate creates a potentially infinite stream from a starting value and a rule that produces each next value.
Generate the first 10 powers of two and the first 10 Fibonacci numbers using streams.
Java Program
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamIterateExample {
public static void main(String[] args) {
List<Integer> powersOfTwo = Stream.iterate(1, x -> x * 2) // 1, 2, 4, 8, ... forever
.limit(10) // so take only the first 10
.collect(Collectors.toList());
List<Integer> fibonacci = Stream.iterate(new int[]{0, 1}, p -> new int[]{p[1], p[0] + p[1]})
.limit(10)
.map(p -> p[0])
.collect(Collectors.toList());
System.out.println("Powers of two: " + powersOfTwo);
System.out.println("Fibonacci: " + fibonacci);
}
}Output
Core Logic
iterate describes how to get from one value to the next, and limit decides how many values to take.
- 1
Stream.iterate(1, x -> x * 2)describes 1, 2, 4, 8, … without end. - 2
limit(10)makes the stream finite, so it can be collected. - 3For Fibonacci, each element is a pair
{a, b}, and the rule produces{b, a + b}. - 4
map(p -> p[0])keeps the first number of each pair.
Key Point: An infinite stream is safe only because it's lazy — forgetting limit makes collect run forever.
Why: Exactly n values are generated and stored in the list.
Key Concepts
Approach 2: iterate with a Stop Condition (Java 9)
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamIterateWithCondition {
public static void main(String[] args) {
String odds = IntStream.iterate(1, x -> x <= 15, x -> x + 2) // Java 9: seed, condition, next
.mapToObj(String::valueOf)
.collect(Collectors.joining(" "));
String countdown = Stream.iterate(5, x -> x > 0, x -> x - 1)
.map(String::valueOf)
.collect(Collectors.joining(", "));
System.out.println("Odd numbers to 15: " + odds);
System.out.println("Countdown: " + countdown);
}
}
Output
Core Logic
Java 9 added an iterate overload with a condition, which reads like a classic for loop: start, keep going while, step.
- 1
IntStream.iterate(1, x -> x <= 15, x -> x + 2)yields the odd numbers up to 15. - 2The stream ends as soon as the condition is false, so no
limitis needed. - 3
Stream.iterate(5, x -> x > 0, x -> x - 1)counts down from 5.
5, 4, 3, 2, 1.Key Point: Use the condition form when the end is defined by a value rather than a count.
Why: One element is produced per step until the condition fails.
Key Concepts
Interview Questions
What's the difference between Stream.iterate and Stream.generate?
iterate computes each value from the previous one; generate calls a Supplier independently each time, for example Stream.generate(Math::random).
Why might Fibonacci overflow here?
An int holds Fibonacci numbers only up to F(46). Use long or BigInteger pairs for longer sequences.