Stream Generate Infinite Limit

Create bounded sequences with Stream.generate plus limit, and verify that no supplier call happens before a terminal operation.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        AtomicInteger sequence = new AtomicInteger();

        // generate calls the supplier for every element when consumed
        List<String> ids = Stream.generate(() -> "id-" + sequence.incrementAndGet())
                .limit(4)
                .toList();
        System.out.println("ids: " + ids);
        System.out.println("supplier calls: " + sequence.get());

        // an infinite stream must always be bounded before collecting
        List<Integer> squares = Stream.generate(new AtomicInteger()::incrementAndGet)
                .map(n -> n * n)
                .limit(5)
                .toList();
        System.out.println("squares: " + squares);

        // generate is lazy: without a terminal operation no supplier runs
        AtomicInteger untouched = new AtomicInteger();
        Stream<String> lazy = Stream.generate(() -> "x" + untouched.incrementAndGet());
        System.out.println("before terminal: " + untouched.get());
        System.out.println("first: " + lazy.findFirst().orElse("none"));
        System.out.println("after terminal: " + untouched.get());
    }
}

How it works

Structurally, expect the class Main and the function main and nothing else.

What to watch for

  • The toolchain alone is enough — no dependency resolution happens.

Using it

The main signature reads public static void main(String[] args)

The run emits 3 labeled sections — ids:, supplier calls:, squares: — one per step.

Key statements

.map(n -> n * n)
.limit(5)
.toList();

Interactive Tools for This Topic

FAQ

What does Stream Generate Infinite Limit print when run?
No setup needed: run the file and look for labeled lines like `ids:`, `supplier calls:`, `squares:` in the output.