Stream.generate() with Suppliers
You'll learn how to create infinite streams that generate elements on-demand using Supplier functions.
What Is Stream.generate()?
Stream.generate() creates an infinite stream by repeatedly calling a Supplier<T> function. Each time the stream needs a new element, it invokes the supplier's get() method. Think of it like a vending machine that never runs out—every time you press the button (request an element), it produces a fresh item.
The Basic Pattern
Stream<String> hellos = Stream.generate(() -> "Hello");
// Creates an infinite stream of "Hello" strings
Without a limiting operation, this stream would generate elements forever. You typically pair it with limit():
Stream.generate(() -> "Hello")
.limit(5)
.forEach(System.out::println);
// Prints "Hello" five times
Stateless Generation
Stream.generate() works best with stateless suppliers—functions that produce independent values without relying on external mutable state:
// Stateless: generates random numbers
Stream.generate(Math::random)
.limit(3)
.forEach(System.out::println);
Each invocation is independent. The supplier doesn't "remember" previous calls or modify shared state.
Why Stateless Matters
While you can use stateful suppliers, it breaks the functional paradigm and causes problems with parallel streams. For sequential generation with state (like counters), Stream.iterate() is better suited.
Common Use Cases
- Generating random test data
- Creating placeholder values
- Simulating infinite sequences of constant values
Key Takeaway:
Stream.generate(Supplier) creates infinite streams by repeatedly invoking a supplier function—best used with stateless suppliers and combined with limiting operations like limit().