Java Reference ยท Streams and Functional
Java Stream limit() and skip()
Reference for Java Stream.limit() and skip(): take the first n elements, drop the first n, build pages, and understand the cost on ordered and parallel streams.
limit(n) truncates a stream to at most n elements, and skip(n) discards the first n. Combined they cut out a window, which is how you implement paging over a stream. Both depend on the stream's encounter order: "first" means first in that order.
limit() is a short-circuiting operation, so it is what makes infinite streams usable. skip() is not: it must still produce the elements it throws away.
List<Integer> page = numbers.stream().skip(20).limit(10).toList();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Stream<T> limit(long maxSize) Stream<T> skip(long n)
| Name | Description |
|---|---|
maxSize |
Maximum number of elements to keep. Must not be negative. |
n |
Number of leading elements to discard. Must not be negative. |
Returns: the sliced stream. Throws: IllegalArgumentException for a negative argument, thrown when the method is called.
Usage notes
- Counts are
long. Convert page arithmetic tolongbefore multiplying to avoidintoverflow. - Over- and under-sized:
limitlarger than the stream, orskipbeyond its end, is fine; you get all elements or none. - Short-circuit:
limitstops pulling from upstream once it has enough, but stages before it run only for the elements actually used. - Parallel and ordered streams: both operations must respect encounter order, which can be expensive in parallel. Call
unordered()first if you only need anynelements. - Not a database page. Skipping 100,000 elements still visits them; for large offsets query by key instead.
- Sorting first:
sorted().limit(n)gives the n smallest, but buffers all input. - Dynamic prefix: to stop at a condition rather than a count use
takeWhile(). List.subList(from, to)is a cheaper O(1) window when the source is already a list.