Course contentsShow
← Java
Lesson 1463 of 2,87032. Streams API: Intermediate OperationsFree lesson

Understanding limit: Taking First N Elements

Learn how limit(n) truncates a stream to at most n elements, enabling controlled processing of large or infinite streams.

Understanding limit: Taking First N Elements

You'll learn how to use limit(n) to cap a stream at a maximum of n elements, giving you precise control over how much data you process.

What Is limit?

The limit(n) operation is an intermediate operation that truncates a stream, keeping at most the first n elements and discarding the rest. Think of it like a gate that only allows the first n items through a pipeline—once the quota is met, everything else is stopped.

This makes limit especially powerful when working with large or even infinite streams (like those from Stream.generate() or Stream.iterate()), where you need to process just a subset of data.

How limit Works

Stream.of("apple", "banana", "cherry", "date", "elderberry")
    .limit(3)
    .forEach(System.out::println);

Output:

apple
banana
cherry

Only the first three elements pass through—date and elderberry are never processed.

Essential with Infinite Streams

Remember those infinite streams you learned earlier? Without limit, they'd run forever:

Stream.iterate(1, n -> n + 1)  // Infinite: 1, 2, 3, 4...
    .limit(5)
    .forEach(System.out::println);  // Prints 1 through 5

Short-Circuiting Behavior

As you learned previously, limit is a short-circuiting intermediate operation. Once n elements have been produced, the upstream operations stop—no wasted computation on elements that would be discarded anyway.

Key Takeaway: limit(n) restricts a stream to at most the first n elements, enabling safe processing of large datasets and making infinite streams practical by providing a clear stopping point.