The limit() method is a handy tool in the Java Stream API that lets you restrict the number of elements flowing through a stream.
✅ What is limit() in Streams?
Stream<T> limit(long maxSize)
📌 Purpose:
- Truncates the stream to contain no more than
maxSizeelements - Returns a new Stream with the first
nelements - Works with ordered streams (like
List,SortedSet, etc.)
🧠 Simple Example:
Stream.of("one", "two", "three", "four")
.limit(2)
.forEach(System.out::println);
// Output:
// one
// two
🔧 Real Use Cases
✅ 1. Paginate results (e.g., first 10 items)
List<String> names = List.of("Anna", "Bob", "Charlie", "David", "Eve");
names.stream()
.limit(3)
.forEach(System.out::println); // Output: Anna, Bob, Charlie
✅ 2. Limit infinite streams
Stream<Integer> infinite = Stream.iterate(0, n -> n + 1);
infinite
.limit(5)
.forEach(System.out::println); // Output: 0 1 2 3 4
⚠️ Without limit(), infinite streams would run forever.
🔄 Common Pairing: skip(n) + limit(n)
Use together for pagination:
List<String> data = List.of("a", "b", "c", "d", "e", "f");
data.stream()
.skip(2) // Skip first 2
.limit(3) // Take next 3
.forEach(System.out::println); // Output: c, d, e
✅ Summary
| Method | limit(long maxSize) |
|---|---|
| 💡 Purpose | Restricts a stream to the first N elements |
| 🧠 Use Case | Trimming results, pagination, controlling infinite streams |
| 💡 Laziness | It’s an intermediate operation — doesn’t execute immediately |