00:00

Java Stream limit() Method

Last updated:

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

Stream.java (API)
// 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.

Usage
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(3) passes three elements and then stops the source A source produces 10, 20, 30, 40 and 50. limit 3 passes 10, 20 and 30 to the next stage. After the third element it signals that it needs no more, so 40 and 50 are never produced. SOURCE limit(3) PASSED ON element 1 10 count = 1 10 element 2 20 count = 2 20 element 3 30 count = 3, done 30 element 4, 5 never produced
Figure 1: 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.

NotificationPreview.java
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");
    }
}
Output
[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.

NextBusinessDays.java
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()));
    }
}
Output
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.

TopDeliveryCities.java
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()));
    }
}
Output
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.

LimitEdgeCases.java
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");
        }
    }
}
Output
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() before filter() 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(); consider unordered() or a sequential stream.

6. limit() vs Related Methods

MethodKeepsShort-circuits?Since
limit(n)The first n elementsYesJava 8
skip(n)Everything after the first nNoJava 8
takeWhile(p)Leading elements while the predicate holdsYesJava 9
findFirst()One element, as an OptionalYes (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

LimitPosition.java
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);
    }
}
Output
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() on generate() or two-argument iterate().
  • Using limit() on a HashSet to get "the first" elements. A hash set has no meaningful order; sort first.
  • Expecting limit() to make sorted() 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