limit() and skip() are intermediate stream operations that control which portion of a stream's elements flow downstream. limit(n) caps the stream at n elements, while skip(n) discards the first n elements.
Key Points: • limit(n) is short-circuiting — it stops processing once n elements have been produced, which matters for infinite streams. • skip(n) is not short-circuiting on its own; it still needs to traverse and discard the first n elements. • The two are commonly combined to implement pagination, e.g. skip(n).limit(pageSize). • Order matters: skip(2).limit(3) behaves differently from limit(3).skip(2) on the same stream. • Both preserve the encounter order of the remaining elements in a sequential stream.
Example: For the list [1,2,3,4,5,6], stream().skip(2).limit(3) returns [3,4,5] — it drops the first two elements, then takes the next three.
Code Example:
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> page = nums.stream()
.skip(2)
.limit(3)
.collect(Collectors.toList());
System.out.println(page); // [3, 4, 5]Interview Tip: A concise interview answer is:
"limit(n) truncates a stream to at most n elements and is short-circuiting, so it works even on infinite streams. skip(n) discards the first n elements before the rest continue downstream. Combining skip() and limit() is a common pattern for implementing pagination over a stream."