00:00

Stream.generate() Method in Java

Last updated:

Stream.generate() is a static method of java.util.stream.Stream, added in Java 8, that returns an infinite, sequential, unordered stream in which every element is produced by calling a Supplier. It is a stream creation operation, and because the stream never ends on its own, you almost always follow it with limit() or another short-circuiting operation.

Use it for values that do not depend on the previous element: constants, random values, new objects or values read from an external source. This tutorial covers the signature, the primitive versions, how to stop the stream, and how it differs from Stream.iterate().

1. Syntax and Method Signature

Stream.java (API)
// java.util.stream.Stream (Java 8)
static <T> Stream<T> generate(Supplier<? extends T> s)

// primitive versions (Java 8)
static IntStream    IntStream.generate(IntSupplier s)
static LongStream   LongStream.generate(LongSupplier s)
static DoubleStream DoubleStream.generate(DoubleSupplier s)

The parameter is a Supplier<? extends T>, a functional interface with one method, T get(), that takes no arguments. The stream calls get() once for every element it needs.

Usage
List<String> placeholders = Stream.generate(() -> "TBD").limit(3).toList();   // [TBD, TBD, TBD]

2. How Stream.generate() Works

generate() does not compute anything up front. When the terminal operation asks for an element, the stream calls the supplier's get() and passes the value down the pipeline. Short-circuiting operations such as limit(), takeWhile(), findFirst() and anyMatch() stop the requests, so the supplier is only called as often as needed.

Each call is independent: the supplier does not receive the previous element. If an element must depend on the one before it, use Stream.iterate(). The stream is unordered, which gives parallel pipelines more freedom; with parallel(), the supplier may be called from several threads, so it must be thread-safe.

Stream.generate() pulls a new value from the Supplier for each element A Supplier is called each time the pipeline needs an element. generate turns the calls into an infinite stream. limit 4 stops the stream after four elements, and toList collects them. The supplier is called exactly four times. Supplierget() each time SUPPLIER generate()infinite, unordered limit(4)stops after 4 toList()4 elements RESULT STREAM Without limit(), a terminal operation such as toList() never finishes.
Figure 1: Each element is a fresh call to the supplier. limit() is what makes the stream finite.

3. Java Examples

Example 1: Repeating a value

Fill a seating plan with five empty seats marked -.

EmptySeats.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class EmptySeats {

    public static void main(String[] args) {
        List<String> seats = Stream.generate(() -> "-")
                .limit(5)
                .collect(Collectors.toList());

        System.out.println(seats);
        System.out.println(String.join("", seats));
    }
}
Output
[-, -, -, -, -]
-----

How it works: The supplier returns the same string every time, and limit(5) takes five copies. For simple repetition, Collections.nCopies(5, "-") and "-".repeat(5) are alternatives.

Example 2: Reproducible random test data

Generate six random dice rolls for a game test. A fixed seed makes the sequence the same on every run.

DiceRolls.java
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class DiceRolls {

    public static void main(String[] args) {
        Random random = new Random(2024);   // fixed seed: same rolls every run

        String rolls = IntStream.generate(() -> random.nextInt(6) + 1)
                .limit(6)
                .mapToObj(String::valueOf)
                .collect(Collectors.joining(" "));

        System.out.println("Rolls: " + rolls);
    }
}
Output
Rolls: 1 3 1 5 6 6

How it works: IntStream.generate() takes an IntSupplier, so the rolls stay int values without boxing. Seeding Random makes tests repeatable. random.ints(6, 1, 7) is a shorter built-in alternative.

Example 3: Creating new objects with a counter (Java 16+)

Create the first four ticket objects for a new event, each with a sequential number.

TicketFactory.java
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TicketFactory {

    record Ticket(String event, int number) { }

    public static void main(String[] args) {
        AtomicInteger counter = new AtomicInteger(100);

        List<Ticket> tickets = Stream.generate(() -> new Ticket("JavaConf", counter.incrementAndGet()))
                .limit(4)
                .collect(Collectors.toList());

        tickets.forEach(System.out::println);
    }
}
Output
Ticket[event=JavaConf, number=101]
Ticket[event=JavaConf, number=102]
Ticket[event=JavaConf, number=103]
Ticket[event=JavaConf, number=104]

How it works: The supplier creates a new object on every call. The shared counter is an AtomicInteger so the supplier stays safe if the stream is later made parallel, although in parallel the numbers could be assigned in a different order. For pure sequences, IntStream.rangeClosed(101, 104) is simpler.

Example 4: Polling until a condition is met (Java 9+)

Read status values from a job queue until it reports DONE, and count how many polls it took.

PollUntilDone.java
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

public class PollUntilDone {

    public static void main(String[] args) {
        Iterator<String> statusFeed = List.of("QUEUED", "RUNNING", "RUNNING", "DONE", "ARCHIVED").iterator();

        long pollsBeforeDone = Stream.generate(statusFeed::next)
                .peek(status -> System.out.println("poll -> " + status))
                .takeWhile(status -> !status.equals("DONE"))
                .count();

        System.out.println("Polls before DONE: " + pollsBeforeDone);
    }
}
Output
poll -> QUEUED
poll -> RUNNING
poll -> RUNNING
poll -> DONE
Polls before DONE: 3

How it works: takeWhile() (Java 9) stops the infinite stream at the first DONE, so ARCHIVED is never read. The supplier here is a method reference to Iterator.next(), standing in for a real status call.

4. Real-World Use Cases

  • Test data: produce many sample customers or orders with a supplier, seeded for repeatable tests.
  • Identifiers: generate a batch of UUID.randomUUID() values or coupon codes.
  • Polling: call a status endpoint repeatedly with takeWhile() until a job finishes (with a delay inside the supplier in real code).
  • Simulations: generate random events, such as customer arrivals, for a capacity model.

5. Important Points

  • Infinite by design: without limit() or another short-circuiting step, collect(), count() or sorted() never finish.
  • Unordered: the stream has no encounter order, so with parallel() and limit() you get some n elements, not necessarily the first n generated.
  • Null values returned by the supplier become null elements.
  • Thread safety: in a parallel pipeline the supplier may run on several threads; use thread-safe state such as AtomicInteger or ThreadLocalRandom.
  • Exceptions thrown by the supplier propagate out of the terminal operation.

6. Stream.generate() vs Related Methods

MethodNext element depends onOrdered?Finite?
Stream.generate(s)Nothing; each call is independentNoInfinite; needs limit()
Stream.iterate(seed, f)The previous elementYesInfinite; needs limit()
Stream.iterate(seed, hasNext, f)The previous elementYesStops when hasNext is false (Java 9)
IntStream.range(a, b)PositionYesFinite

Choose generate() for independent values, and iterate() for sequences such as counters, dates or doubling values.

7. Common Mistakes and Best Practices

Forgetting limit()

Wrong
List<String> ids = Stream.generate(() -> UUID.randomUUID().toString()).toList();   // never returns

Always bound the stream before a terminal operation that needs every element:

BoundedIds.java
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class BoundedIds {

    public static void main(String[] args) {
        List<String> ids = Stream.generate(() -> UUID.randomUUID().toString())
                .limit(3)
                .collect(Collectors.toList());

        System.out.println("Generated " + ids.size() + " ids, each " + ids.get(0).length() + " characters long");
    }
}
Output
Generated 3 ids, each 36 characters long

Other mistakes to avoid

  • Using generate() for a counter. iterate() or IntStream.range() express sequences without shared state.
  • Expecting the first n elements in parallel. The stream is unordered; keep it sequential if position matters.
  • Sharing a non-thread-safe Random in parallel. Use ThreadLocalRandom.current() inside the supplier.

8. Summary

  • Stream.generate() creates an infinite, unordered stream from a Supplier.
  • Each element is an independent call to get(); the supplier does not see the previous element.
  • Bound it with limit(), takeWhile() or a short-circuiting terminal operation.
  • Use the primitive versions to avoid boxing, and thread-safe state if the stream may run in parallel.

9. References