Java Programs›Java 8 Streams›Generate Sequences Using Stream.iterate()

Generate Sequences Using Stream.iterate() in Java

intermediate·  Java 8 Streams  ·  Streams

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.

Input
seed 1, rule x * 2
Output
[1, 2, 4, ..., 512]

Java Program

Java
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

Powers of two: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Core Logic

iterate describes how to get from one value to the next, and limit decides how many values to take.

How It Works
  1. 1Stream.iterate(1, x -> x * 2) describes 1, 2, 4, 8, … without end.
  2. 2limit(10) makes the stream finite, so it can be collected.
  3. 3For Fibonacci, each element is a pair {a, b}, and the rule produces {b, a + b}.
  4. 4map(p -> p[0]) keeps the first number of each pair.
The pairs go {0, 1}, {1, 1}, {1, 2}, {2, 3}, …, so the first numbers are 0, 1, 1, 2, 3, …
💡

Key Point: An infinite stream is safe only because it's lazy — forgetting limit makes collect run forever.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: Exactly n values are generated and stored in the list.

Key Concepts

Stream.iterate()limit()infinite streamsarray as state

Approach 2: iterate with a Stop Condition (Java 9)

Java
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

Odd numbers to 15: 1 3 5 7 9 11 13 15 Countdown: 5, 4, 3, 2, 1

Core Logic

Java 9 added an iterate overload with a condition, which reads like a classic for loop: start, keep going while, step.

How It Works
  1. 1IntStream.iterate(1, x -> x <= 15, x -> x + 2) yields the odd numbers up to 15.
  2. 2The stream ends as soon as the condition is false, so no limit is needed.
  3. 3Stream.iterate(5, x -> x > 0, x -> x - 1) counts down from 5.
The countdown prints 5, 4, 3, 2, 1.
💡

Key Point: Use the condition form when the end is defined by a value rather than a count.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: One element is produced per step until the condition fails.

Key Concepts

iterate(seed, hasNext, next)IntStream.iterateCollectors.joining

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.

Learn the Concept

Related Programs