Course contentsShow
← Java
Lesson 1378 of 2,87031. Streams API: Creation and BasicsFree lesson

Stream.iterate() with Seed and UnaryOperator

Create sequential streams using an initial value and iteration function for arithmetic sequences.

Stream.iterate() with Seed and UnaryOperator

What You'll Learn

You'll learn how to create sequential, infinite streams using Stream.iterate() by providing a starting value and a function that generates each subsequent element.

The Core Idea

Stream.iterate() creates a stream by repeatedly applying a function to a value. You provide two things:

  1. Seed: The initial value (where your sequence starts)
  2. UnaryOperator: A function that takes the previous value and produces the next one

Think of it like a mathematical sequence where each term depends on the one before it. For example, the sequence 0, 2, 4, 6, 8... starts at 0 (the seed) and adds 2 to get the next number (the operator).

Unlike Stream.generate(), which produces independent values, iterate() builds each element from the previous one—perfect for arithmetic sequences, progressions, or any pattern where each step depends on the last.

Basic Syntax

Stream<Integer> evenNumbers = Stream.iterate(0, n -> n + 2);
// Produces: 0, 2, 4, 6, 8, 10, 12...

The first argument (0) is your seed. The second (n -> n + 2) is a UnaryOperator<Integer> that defines how to get from one element to the next.

Practical Examples

// Powers of 2: 1, 2, 4, 8, 16...
Stream.iterate(1, n -> n * 2)
      .limit(5)
      .forEach(System.out::println);

// Countdown: 10, 9, 8, 7...
Stream.iterate(10, n -> n - 1)
      .limit(10)
      .forEach(System.out::println);

Remember: iterate() produces infinite streams, so you must use limit() or another short-circuiting operation to avoid running forever.

Analogy

Think of iterate() as a snowball rolling downhill. The seed is your starting snowball, and the UnaryOperator describes how it grows with each roll—always building on what came before.

Key Takeaway: Stream.iterate(seed, function) creates infinite sequential streams by repeatedly applying a UnaryOperator to generate each element from its predecessor, ideal for arithmetic or mathematical sequences.