Java Stream limit() Method
limit() is a short-circuiting stateful intermediate operation of java.util.stream.Stream, available since Java 8, that returns a stream of at most n elements: the first n in encounter order. Once it has passed n elements, it stops pulling from the source.
It is how you take the top results of a report, page through data together with skip(), and turn infinite streams into finite ones. This tutorial covers its signature, short-circuiting, edge cases and its cost in parallel streams.
1. Syntax and Method Signature
// java.util.stream.Stream<T> (Java 8)
Stream<T> limit(long maxSize)
// primitive versions
IntStream IntStream.limit(long maxSize)
maxSize is a long, the maximum number of elements to keep. A negative value throws IllegalArgumentException immediately. The result has the same element type. No functional interface is involved.
List<Product> topFive = products.stream()
.sorted(Comparator.comparingInt(Product::sales).reversed())
.limit(5)
.toList();
2. How limit() Works
limit() keeps a counter. Each element that arrives is passed on and counted; when the counter reaches maxSize, the stage tells the source that no more elements are needed. Upstream stages therefore stop doing work too, which is why Stream.iterate(...).limit(10) terminates.
It is stateful because it must count, and short-circuiting because it can finish before the source is exhausted. On ordered sequential streams it is cheap. On ordered parallel streams it must return the first n elements in encounter order, which may require buffering; if any n elements will do, call unordered() first.
limit() counts the elements it passes on. After the limit is reached it cancels the rest of the stream, which is what makes infinite sources usable.3. Java Examples
Example 1: Taking the first n elements (Java 9+)
Show only the first three notifications in a preview panel.
import java.util.List;
import java.util.stream.Collectors;
public class NotificationPreview {
public static void main(String[] args) {
List<String> notifications = List.of(
"Payment received", "New follower", "Password changed", "Weekly report ready", "Offer expires today");
List<String> preview = notifications.stream()
.limit(3)
.collect(Collectors.toList());
System.out.println(preview);
System.out.println("+" + (notifications.size() - preview.size()) + " more");
}
}
[Payment received, New follower, Password changed] +2 more
How it works: limit(3) keeps the first three elements in encounter order, which for a list is index order.
Example 2: Making an infinite stream finite
Generate the first six business days starting from a Friday, skipping weekends.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.stream.Stream;
public class NextBusinessDays {
public static void main(String[] args) {
LocalDate friday = LocalDate.of(2026, 11, 27);
Stream.iterate(friday, d -> d.plusDays(1))
.filter(d -> d.getDayOfWeek() != DayOfWeek.SATURDAY && d.getDayOfWeek() != DayOfWeek.SUNDAY)
.limit(6)
.forEach(d -> System.out.println(d + " " + d.getDayOfWeek()));
}
}
2026-11-27 FRIDAY 2026-11-30 MONDAY 2026-12-01 TUESDAY 2026-12-02 WEDNESDAY 2026-12-03 THURSDAY 2026-12-04 FRIDAY
How it works: The date stream is infinite. limit(6) after the filter counts only business days, so the pipeline stops once six of them have passed.
Example 3: Top n after sorting (Java 9+)
List the three cities with the most deliveries this week.
import java.util.Comparator;
import java.util.Map;
public class TopDeliveryCities {
public static void main(String[] args) {
Map<String, Integer> deliveries = Map.of(
"Kochi", 340, "Nagpur", 515, "Ranchi", 120, "Vizag", 480, "Udaipur", 295);
deliveries.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder()))
.limit(3)
.forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
}
}
Nagpur: 515 Vizag: 480 Kochi: 340
How it works: Sorting must see every entry, but limit(3) then passes only the first three to forEach(). Map.Entry.comparingByValue() builds the comparator for the entries.
Example 4: Edge cases
Check what limit() does with zero, a value larger than the stream, and a negative value.
import java.util.stream.Stream;
public class LimitEdgeCases {
public static void main(String[] args) {
System.out.println("limit(0): " + Stream.of("a", "b", "c").limit(0).count());
System.out.println("limit(10): " + Stream.of("a", "b", "c").limit(10).count());
try {
Stream.of("a", "b", "c").limit(-1);
} catch (IllegalArgumentException e) {
System.out.println("limit(-1): IllegalArgumentException");
}
}
}
limit(0): 0 limit(10): 3 limit(-1): IllegalArgumentException
How it works: A limit larger than the stream simply returns every element. limit(0) gives an empty stream. A negative limit is rejected as soon as limit() is called, before any terminal operation.
4. Real-World Use Cases
- Top-n reports: best-selling products, slowest endpoints, largest accounts.
- Pagination:
skip(page * size).limit(size)for in-memory paging. - Bounded generation: the next n invoice numbers, dates or test records from an infinite source.
- Previews: the first few lines of a file or a feed.
5. Important Points
- Order matters: on ordered streams you get the first n in encounter order; on unordered ones, any n.
- Position in the pipeline:
limit()beforefilter()takes n elements then filters them; after it, it takes n matches. - Does not reduce sorting work:
sorted().limit(3)still sorts everything. - Large values are fine; there is no extra cost for a limit bigger than the stream.
- Parallel ordered streams can be slow with
limit(); considerunordered()or a sequential stream.
6. limit() vs Related Methods
| Method | Keeps | Short-circuits? | Since |
|---|---|---|---|
limit(n) | The first n elements | Yes | Java 8 |
skip(n) | Everything after the first n | No | Java 8 |
takeWhile(p) | Leading elements while the predicate holds | Yes | Java 9 |
findFirst() | One element, as an Optional | Yes (terminal) | Java 8 |
Use limit() for a count, and takeWhile() when the stopping point depends on the values; see skip() for paging.
7. Common Mistakes and Best Practices
Putting limit() in the wrong place
import java.util.List;
import java.util.stream.IntStream;
public class LimitPosition {
public static void main(String[] args) {
List<Integer> limitThenFilter = IntStream.rangeClosed(1, 20).boxed()
.limit(5).filter(n -> n % 2 == 0).toList();
List<Integer> filterThenLimit = IntStream.rangeClosed(1, 20).boxed()
.filter(n -> n % 2 == 0).limit(5).toList();
System.out.println("limit then filter: " + limitThenFilter);
System.out.println("filter then limit: " + filterThenLimit);
}
}
limit then filter: [2, 4] filter then limit: [2, 4, 6, 8, 10]
If you want the first five even numbers, filter first. If you want the even numbers among the first five, limit first.
Other mistakes to avoid
- Forgetting
limit()ongenerate()or two-argumentiterate(). - Using
limit()on aHashSetto get "the first" elements. A hash set has no meaningful order; sort first. - Expecting
limit()to makesorted()cheap. Use a bounded priority queue for top-n over huge data.
8. Summary
limit(n)keeps at most the first n elements and then stops the source.- It is stateful and short-circuiting, which lets infinite streams finish.
- Its position in the pipeline changes the meaning: filter then limit, or limit then filter.
- Negative values throw
IllegalArgumentException; ordered parallel streams make it costly.
9. References
Frequently Asked Questions (FAQ)
Q1. What does limit() do in Java streams?
limit(n) is a short-circuiting stateful intermediate operation that returns a stream of at most n elements, the first n in encounter order, and then stops pulling from the source.
Q2. Is limit() short-circuiting?
Yes. Once it has passed n elements it cancels the rest of the stream, so upstream stages stop working. That is why it can make an infinite stream finite.
Q3. What happens if the limit is larger than the stream?
Every element is returned; there is no error. limit(0) returns an empty stream, and a negative limit throws IllegalArgumentException.
Q4. How do I paginate with streams?
Combine skip() and limit(): stream.skip((long) page * size).limit(size) returns one page, with pages counted from zero. For database data, page in the query instead.
Q5. Why is limit() slow on parallel streams?
On ordered parallel streams it must return exactly the first n elements in encounter order, which needs coordination and buffering across threads. If any n elements are acceptable, call unordered() first.