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.
int[] counter = {0};
List<Integer> ticks = Stream.generate(() -> counter[0]++)
.limit(5)
.toList();
System.out.println("Generated ticks: " + ticks);
Generated ticks: [0, 1, 2, 3, 4]
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