Order Preservation with limit and skip
You'll learn how limit and skip interact with stream ordering, and what happens when order isn't guaranteed.
How Order Works with limit and skip
Both limit and skip are encounter-order aware operations. This means they respect and preserve the order in which elements are encountered in the stream.
In ordered streams, the behavior is predictable:
skip(n)discards the first n elementslimit(n)takes the first n elements after any previous operations
Think of it like a queue at a ticket counter: skip(3) lets the first 3 people leave without service, and limit(5) serves exactly the next 5 people in line.
List<String> names = List.of("Alice", "Bob", "Charlie", "Diana", "Eve");
names.stream()
.skip(1)
.limit(3)
.forEach(System.out::println);
// Output: Bob, Charlie, Diana (deterministic order)
Unordered Streams Change Everything
When a stream has no encounter order (like from a HashSet or after calling .unordered()), limit and skip still work, but:
- Which elements are skipped becomes unpredictable
- Which elements are taken by limit becomes unpredictable
- The operations may perform faster because ordering constraints are relaxed
Set<String> unorderedSet = new HashSet<>(names);
unorderedSet.stream()
.skip(1)
.limit(3)
.forEach(System.out::println);
// Output: unpredictable which 3 of 4 remaining elements appear
Why This Matters
Ordering guarantees affect correctness in pagination, windowing, and parallel processing. If you need deterministic results with limit and skip, ensure your source has encounter order (like List) or explicitly sort first.
Key Takeaway:
limit and skip preserve encounter order in ordered streams, making them deterministic; in unordered streams, they still work but element selection becomes unpredictable.