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

Limiting Infinite Streams from generate()

Combine Stream.generate() with limit() to create bounded streams from infinite sources.

Limiting Infinite Streams from generate()

You'll learn how to transform an endless stream into a finite, usable sequence by combining Stream.generate() with limit().

The Problem with Infinite Streams

As you've seen, Stream.generate() creates an infinite stream—it will keep producing elements forever. This is powerful but dangerous: if you try to consume an infinite stream without constraints, your program will never finish (or worse, crash from memory exhaustion).

Think of Stream.generate() like a faucet that never turns off. You need to place a bucket underneath to catch exactly the amount of water you need.

Using limit() to Bound the Stream

The limit(long maxSize) intermediate operation does exactly this—it truncates a stream to at most maxSize elements. When combined with generate(), it creates a bounded stream from an infinite source:

Stream<Double> randomNumbers = Stream.generate(Math::random)
                                     .limit(5);

randomNumbers.forEach(System.out::println);
// Prints exactly 5 random numbers, then stops

Here, generate() would produce random numbers forever, but limit(5) stops the pipeline after 5 elements.

How It Works

When a terminal operation (like forEach) starts the pipeline, it pulls elements one by one. The limit() operation acts as a gatekeeper: it passes through elements until it has allowed the specified number, then signals the pipeline to stop. This prevents the infinite source from ever being asked for more elements.

Stream.generate(() -> "Echo")
      .limit(3)
      .forEach(System.out::println);
// Output:
// Echo
// Echo
// Echo

Key Takeaway: Always use limit() with infinite streams like those from Stream.generate() to create bounded, consumable sequences. Without it, your stream will never terminate.