Limit Stream

limit(n) is a short-circuiting intermediate Stream operation that truncates the stream to at most the first n elements in encounter order.

Key Points: • limit(n) stops pulling elements from the source as soon as n elements have been produced, which is especially valuable on infinite streams. • If the stream has fewer than n elements, limit() simply returns all of them without error. • It's often paired with skip() to implement pagination, e.g. skip(offset).limit(pageSize). • Because it's short-circuiting, limit() lets you safely operate on infinite streams like Stream.iterate() without hanging. • On unordered parallel streams, which specific elements are kept isn't strictly guaranteed to match sequential encounter order.

Example: Given the list [10, 20, 30, 40, 50], calling limit(3) produces a stream yielding just 10, 20, 30.

Code Example:

List<Integer> limited = numbers.stream()
        .limit(3)
        .collect(Collectors.toList());

Interview Tip: A concise interview answer is:

"limit(n) truncates a stream to at most n elements and is short-circuiting, which makes it essential when working with infinite streams like Stream.iterate() - without it the pipeline would never terminate."