Stream.generate() Method in Java
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
// 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.
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.
limit() is what makes the stream finite.3. Java Examples
Example 1: Repeating a value
Fill a seating plan with five empty seats marked -.
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));
}
}
[-, -, -, -, -] -----
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.
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);
}
}
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.
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);
}
}
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.
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);
}
}
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()orsorted()never finish. - Unordered: the stream has no encounter order, so with
parallel()andlimit()you get some n elements, not necessarily the first n generated. - Null values returned by the supplier become
nullelements. - Thread safety: in a parallel pipeline the supplier may run on several threads; use thread-safe state such as
AtomicIntegerorThreadLocalRandom. - Exceptions thrown by the supplier propagate out of the terminal operation.
6. Stream.generate() vs Related Methods
| Method | Next element depends on | Ordered? | Finite? |
|---|---|---|---|
Stream.generate(s) | Nothing; each call is independent | No | Infinite; needs limit() |
Stream.iterate(seed, f) | The previous element | Yes | Infinite; needs limit() |
Stream.iterate(seed, hasNext, f) | The previous element | Yes | Stops when hasNext is false (Java 9) |
IntStream.range(a, b) | Position | Yes | Finite |
Choose generate() for independent values, and iterate() for sequences such as counters, dates or doubling values.
7. Common Mistakes and Best Practices
Forgetting limit()
List<String> ids = Stream.generate(() -> UUID.randomUUID().toString()).toList(); // never returns
Always bound the stream before a terminal operation that needs every element:
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");
}
}
Generated 3 ids, each 36 characters long
Other mistakes to avoid
- Using
generate()for a counter.iterate()orIntStream.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
Randomin parallel. UseThreadLocalRandom.current()inside the supplier.
8. Summary
Stream.generate()creates an infinite, unordered stream from aSupplier.- 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
Frequently Asked Questions (FAQ)
Q1. What does Stream.generate() return?
It returns an infinite, sequential, unordered stream whose elements are produced by calling the given Supplier's get() method once per element.
Q2. How do I stop an infinite stream from Stream.generate()?
Use a short-circuiting operation such as limit(n), takeWhile() (Java 9), findFirst() or anyMatch(). Without one, a terminal operation that needs every element never finishes.
Q3. What is the difference between Stream.generate() and Stream.iterate()?
generate() calls a Supplier that does not see the previous element, so each value is independent. iterate() applies a function to the previous element, producing an ordered sequence such as 1, 2, 4, 8.
Q4. Is the stream from Stream.generate() ordered?
No. The documentation describes it as an unordered stream. In a sequential pipeline the values appear in the order they are generated, but with parallel() and limit() you are not guaranteed the first n values generated.
Q5. Can Stream.generate() be used with primitive types?
Yes. IntStream.generate(), LongStream.generate() and DoubleStream.generate() take IntSupplier, LongSupplier and DoubleSupplier and avoid boxing.