skip(n) is a Stream API intermediate operation that discards the first n elements of a stream, passing the rest through to subsequent operations.
Key Points: • skip(n) returns a new stream without the first n elements, leaving the original source untouched. • If n is greater than the stream's size, skip() simply returns an empty stream rather than throwing an error. • It's commonly combined with limit() to implement pagination over a stream. • skip() is a stateful intermediate operation, so on infinite or ordered streams it needs to buffer or track position, which can affect performance. • Elements are skipped based on encounter order, so skip() behaves predictably on ordered sources like lists.
Example: Given the list [1, 2, 3, 4, 5], calling skip(2) drops 1 and 2, leaving a stream of [3, 4, 5] for the rest of the pipeline.
Code Example:
List<Integer> skipped = numbers.stream()
.skip(2)
.collect(Collectors.toList());Interview Tip: A concise interview answer is:
"skip(n) drops the first n elements of a stream and passes the rest along, which I typically combine with limit() to implement pagination - for example skip(20).limit(10) for page three of a ten-item page size."