Understanding skip: Discarding First N Elements
You'll learn how to use skip(n) to discard the first n elements from a stream, enabling pagination and skipping unwanted prefixes.
What skip Does
The skip(long n) operation is an intermediate operation that discards the first n elements of a stream and returns a new stream containing the remaining elements. Think of it like skipping tracks on a playlist—you jump past the first few songs to get to the one you actually want to hear.
If the stream has fewer than n elements, skip returns an empty stream. If n is zero or negative, skip returns the original stream unchanged.
Basic Usage
List<String> days = List.of("Mon", "Tue", "Wed", "Thu", "Fri");
// Skip first 2 days
days.stream()
.skip(2)
.forEach(System.out::println);
// Output: Wed, Thu, Fri
Practical Applications
Pagination is a common use case. Combine skip with limit to retrieve specific pages of data:
int page = 2;
int pageSize = 10;
items.stream()
.skip((long) page * pageSize) // Skip previous pages
.limit(pageSize) // Take current page
.forEach(System.out::println);
Skipping Headers in data files:
lines.stream()
.skip(1) // Skip header row
.map(line -> line.split(","))
.forEach(fields -> processData(fields));
Performance Note
Like limit, skip is a stateful intermediate operation but typically performs well since it only needs to count and discard elements, not buffer them.
Key Takeaway: Use skip(n) to bypass the first n elements of a stream, especially useful for pagination scenarios and skipping prefixes like file headers.