Streams: Stream.generate pairs with limit to build a bounded stream from a Supplier

Stream.generate produces an infinite stream by calling a Supplier repeatedly, so it must be paired with limit (or another short-circuit) or the pipeline never terminates.

Code
int[] counter = {0};
List<Integer> ticks = Stream.generate(() -> counter[0]++)
        .limit(5)
        .toList();
System.out.println("Generated ticks: " + ticks);
Output
Generated ticks: [0, 1, 2, 3, 4]
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms