Combining limit and skip for Pagination
You'll learn how to extract specific "pages" of data from a stream by chaining skip() and limit() together.
Pagination is a common pattern where you divide data into chunks (pages) and retrieve one chunk at a time. Think of browsing search results: instead of seeing all 10,000 results at once, you see 10 per page and navigate between pages.
The Core Pattern
By combining skip() and limit(), you can select any range of elements from a stream:
Stream<String> results = Stream.of("item1", "item2", "item3", "item4",
"item5", "item6", "item7", "item8");
// Page 2 with page size 3: skip first 3, take next 3
List<String> page2 = results
.skip(3) // Skip page 1 (items 0-2)
.limit(3) // Take only 3 items
.collect(Collectors.toList());
// Result: [item4, item5, item6]
The Pagination Formula
For page N (0-indexed) with page size P:
- Skip:
N × Pelements - Limit:
Pelements
int pageNumber = 2; // third page (0-indexed)
int pageSize = 5;
List<Product> page = allProducts.stream()
.skip((long) pageNumber * pageSize)
.limit(pageSize)
.collect(Collectors.toList());
Why Order Matters
Always use skip() before limit(). Using limit() first would restrict your stream too early, and then skip() would remove items you wanted to keep.
Short-Circuiting Efficiency
Remember that limit() short-circuits, so the stream won't process more elements than necessary. This makes pagination efficient even on large data sources.
Key Takeaway: Pagination in streams follows the pattern .skip(pageNumber × pageSize).limit(pageSize), efficiently extracting any range of elements without processing the entire dataset.