Stream.limit()
Truncates a stream to its first N elements.
Available since: Java 8
Syntax
Stream<T> limit(long maxSize)Parameters
| Parameter | Type | Description |
|---|---|---|
| maxSize | long | The maximum number of elements. |
Return value
Stream<T>A stream no longer than `maxSize`.
Examples
The first three elements:
void main() {
IO.println(Stream.of("a", "b", "c", "d", "e").limit(3).toList());
}Output:
[a, b, c]Notes
It makes an infinite stream from iterate() or generate() finite. If there are fewer elements than maxSize, all of them are returned. Together with skip() it is used for pagination.
See also
- Stream.skip() — Skips the first N elements of a stream.
- Stream.iterate() — Creates a stream where each element is computed from the previous one.
- Stream.takeWhile() — Takes elements while a condition holds and stops at the first one that fails it.
- List.subList() — Returns the part of a list between two indexes.
Related recipes
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.