Java Stream limit, skip, takeWhile, concat, distinct, sorted and peek
Cut, combine and reorder Java streams: limit and skip (with paging), takeWhile and dropWhile versus filter, Stream.concat, distinct, stable sorted with comparators, and peek for debugging, including why peek can silently not run with count().
kvi5hnuCode Sprout team member9 min readOn this page
filter, map and flatMap change which elements a stream has and what they are. The operations in this article deal with position and order. limit, skip, takeWhile and dropWhile extract part of a stream, concat joins two streams, distinct removes duplicates, sorted reorders, and peek lets you watch elements go by. They're all intermediate operations, but they don't all behave the same way under the hood, and that matters for infinite streams and for performance.
Extracting substreams
limit and skip
stream.limit(n) returns a stream that ends after n elements, or earlier if the original stream is shorter. It's the standard way to cut an infinite stream down to size:
Stream<Double> randoms = Stream.generate(Math::random).limit(100); // 100 random numbers
stream.skip(n) does the opposite: it discards the first n elements and keeps the rest. A practical example is the leading empty string from split. When text starts with a delimiter, "...Down the rabbit hole!".split("\\PL+") returns ["", "Down", "the", "rabbit", "hole"], because there is an empty field before the first match. (Trailing empty strings are removed by split, leading ones are not.) skip(1) gets rid of it.
Together, skip and limit give you paging:
List<Item> page = items.stream()
.skip((long) (pageNumber - 1) * pageSize)
.limit(pageSize)
.toList();
That's handy for in-memory data. For database results, let the database do the paging (LIMIT/OFFSET in SQL, Part 5) instead of loading all rows to skip most of them.
takeWhile and dropWhile
takeWhile(predicate) (Java 9) takes elements while the predicate is true and stops at the first element that fails it. dropWhile(predicate) does the opposite: it discards elements while the predicate is true and then passes through everything from the first failure onward, even later elements that would match again.
Stream<String> initialDigits = graphemeClusters("42 apples").takeWhile(s -> "0123456789".contains(s)); // "4", "2"
Stream<String> withoutLeadingBlanks = graphemeClusters(" indented").dropWhile(String::isBlank);
The difference from filter is easy to overlook. For the temperatures 3, 5, 9, 12, 4, 15:
Operation with t < 10 | Result |
|---|---|
filter | 3, 5, 9, 4, every matching element |
takeWhile | 3, 5, 9, the matching prefix |
dropWhile | 12, 4, 15, everything after the prefix |
Because takeWhile stops at the first failure, it can end an infinite stream: Stream.iterate(1, n -> n * 2).takeWhile(n -> n < 1000) yields the powers of two below 1,000. With filter in place of takeWhile, the pipeline would never terminate. filter has no way of knowing that no later element can match.
Combining streams with concat
The static Stream.concat(a, b) returns a stream of all elements of a followed by all elements of b:
Stream<String> combined = Stream.concat(graphemeClusters("Hello"), graphemeClusters("World"));
// "H", "e", "l", "l", "o", "W", "o", "r", "l", "d"
The first stream shouldn't be infinite, or the second one never gets a turn. concat takes exactly two streams. To join many, don't nest concat calls in a loop. Each nesting level adds a layer of wrapping, and very deep nesting can even cause a StackOverflowError, as the Javadoc warns. Use flatMap instead:
Stream.of(streamA, streamB, streamC).flatMap(s -> s) // or .flatMap(Function.identity())
Other transformations
distinct
distinct() keeps the first occurrence of each element and drops later duplicates, keeping the original order. The duplicates don't have to be adjacent. Equality is decided by equals and hashCode, just like in a HashSet, so records and well-written value classes work out of the box, and classes that don't override equals count every object as distinct.
sorted
sorted() sorts elements that implement Comparable. sorted(comparator) uses any Comparator, and the comparator combinators from the first course combine nicely here:
Stream<String> longestFirst = words.stream().sorted(Comparator.comparing(String::length).reversed());
The sort is stable for ordered streams: elements that compare as equal keep their relative order. In the demo, "gently" stays ahead of "stream" because it came first, even though both have six letters.
You can sort a list in place with list.sort(...) without any stream. sorted is for when sorting is one step in a longer pipeline.
peek
peek(action) returns a stream with the same elements and calls action on each element as it passes by. It exists for debugging:
Object[] powers = Stream.iterate(1.0, p -> p * 2)
.peek(e -> System.out.println("Fetching " + e))
.limit(20)
.toArray();
The messages confirm that the infinite stream is processed lazily: only 20 elements are ever fetched.
Don't use peek for real work, like adding elements to a list or updating a counter. The stream library is allowed to skip operations that can't affect the result. Since Java 9, count() on a stream whose size is known up front, such as a list's stream with only size-preserving steps like map or peek, simply returns the size without running the pipeline at all. In the demo, list.stream().peek(...).count() prints nothing. Add a filter, and the size is no longer known in advance, so the elements flow through and peek runs.
A complete example
import java.util.*;
import java.util.stream.*;
public class Solution {
static Stream<String> graphemeClusters(String s) {
return Stream.of(s.split("\\b{g}"));
}
public static void main(String[] args) {
// limit and skip
System.out.println("limit(5): " + Stream.iterate(1, n -> n + 1).limit(5).toList());
System.out.println("skip(5): " + Stream.iterate(1, n -> n + 1).skip(5).limit(5).toList());
String text = "...Down the rabbit hole!";
System.out.println("split: " + Arrays.toString(text.split("\\PL+")));
System.out.println("skip(1): " + Stream.of(text.split("\\PL+")).skip(1).toList());
int page = 2, pageSize = 3;
List<String> items = List.of("a", "b", "c", "d", "e", "f", "g", "h");
System.out.println("page 2: " + items.stream().skip((long) (page - 1) * pageSize).limit(pageSize).toList());
// takeWhile and dropWhile look at a prefix
String order = "42 apples, 7 pears";
System.out.println("takeWhile: " + graphemeClusters(order).takeWhile(s -> "0123456789".contains(s)).toList());
System.out.println("dropWhile: " + String.join("", graphemeClusters(" indented").dropWhile(s -> s.isBlank()).toList()));
// unlike filter, they stop at the first mismatch
List<Integer> temps = List.of(3, 5, 9, 12, 4, 15);
System.out.println("filter(<10): " + temps.stream().filter(t -> t < 10).toList());
System.out.println("takeWhile(<10): " + temps.stream().takeWhile(t -> t < 10).toList());
System.out.println("dropWhile(<10): " + temps.stream().dropWhile(t -> t < 10).toList());
// takeWhile can end an infinite stream
System.out.println("powers < 1000: " + Stream.iterate(1, n -> n * 2).takeWhile(n -> n < 1000).toList());
// concat
System.out.println("concat: " + Stream.concat(graphemeClusters("Hello"), graphemeClusters("World")).toList());
System.out.println("of+flatMap: " + Stream.of(List.of(1, 2), List.of(3), List.of(4, 5))
.flatMap(List::stream).toList());
// distinct keeps the first occurrence, duplicates need not be adjacent
System.out.println("distinct: " + Stream.of("merrily", "gently", "merrily", "down", "merrily").distinct().toList());
// sorted, natural or with a comparator; the sort is stable
List<String> words = List.of("row", "your", "boat", "gently", "down", "the", "stream");
System.out.println("sorted: " + words.stream().sorted().toList());
System.out.println("longest first: " + words.stream()
.sorted(Comparator.comparing(String::length).reversed()).toList());
System.out.println("by length, stable: " + words.stream()
.sorted(Comparator.comparing(String::length)).toList());
System.out.println("case-insensitive: " + Stream.of("banana", "Cherry", "apple")
.sorted(String.CASE_INSENSITIVE_ORDER).toList());
// peek shows when elements are actually fetched
List<Double> powers = Stream.iterate(1.0, p -> p * 2)
.peek(e -> System.out.println(" fetching " + e))
.limit(4)
.toList();
System.out.println("powers: " + powers);
// peek is not guaranteed to run: count() can skip the pipeline
long n = List.of("x", "y", "z").stream()
.peek(e -> System.out.println(" peek saw " + e))
.count();
System.out.println("count = " + n + " (peek printed nothing)");
long m = List.of("x", "y", "z").stream()
.filter(e -> true)
.peek(e -> System.out.println(" peek saw " + e))
.count();
System.out.println("count = " + m + " (with filter, the size is unknown, so peek ran)");
// sorted must see everything before it can emit anything
List<Integer> firstAfterSort = Stream.of(5, 3, 8, 1)
.peek(e -> System.out.println(" before sort: " + e))
.sorted()
.peek(e -> System.out.println(" after sort: " + e))
.limit(1)
.toList();
System.out.println("smallest: " + firstAfterSort);
}
}
limit(5): [1, 2, 3, 4, 5]
skip(5): [6, 7, 8, 9, 10]
split: [, Down, the, rabbit, hole]
skip(1): [Down, the, rabbit, hole]
page 2: [d, e, f]
takeWhile: [4, 2]
dropWhile: indented
filter(<10): [3, 5, 9, 4]
takeWhile(<10): [3, 5, 9]
dropWhile(<10): [12, 4, 15]
powers < 1000: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
concat: [H, e, l, l, o, W, o, r, l, d]
of+flatMap: [1, 2, 3, 4, 5]
distinct: [merrily, gently, down]
sorted: [boat, down, gently, row, stream, the, your]
longest first: [gently, stream, your, boat, down, row, the]
by length, stable: [row, the, your, boat, down, gently, stream]
case-insensitive: [apple, banana, Cherry]
fetching 1.0
fetching 2.0
fetching 4.0
fetching 8.0
powers: [1.0, 2.0, 4.0, 8.0]
count = 3 (peek printed nothing)
peek saw x
peek saw y
peek saw z
count = 3 (with filter, the size is unknown, so peek ran)
before sort: 5
before sort: 3
before sort: 8
before sort: 1
after sort: 1
smallest: [1]
Common questions
How do I remove duplicates by a key, such as people with the same email?
distinct always uses the elements' own equals. For a key, the simplest sequential solution is a filter that remembers the keys it has seen: Set<String> seen = new HashSet<>(); people.stream().filter(p -> seen.add(p.email())). It keeps the first person for each email. The lambda has state, so it is not safe for parallel streams. A collector-based alternative is toMap(Person::email, p -> p, (first, second) -> first, LinkedHashMap::new).values(), and article 15 shows a reusable "distinct by" gatherer.
How do I sort in descending order, or by several fields?
Use the comparator combinators: sorted(Comparator.reverseOrder()) for natural descending order, sorted(Comparator.comparing(Person::age).reversed()) for a key, and comparing(Person::lastName).thenComparing(Person::firstName) for several fields. Comparator.nullsFirst(...) and nullsLast(...) handle null keys.
What does skip(10) do on a stream with only 5 elements?
It returns an empty stream; no exception. Likewise, limit(10) on a shorter stream simply passes all elements.
Are limit and skip slow on parallel streams?
They can be. On an ordered parallel stream they must respect the encounter order, which forces threads to coordinate and buffer elements. If you only need some n elements, call unordered() first, and the limit becomes cheap. Sequential streams are not affected.
Why do I get the same order back from sorted() that I put in, for equal elements?
Because sorting an ordered stream is stable: equal elements keep their relative order. That makes multi-step sorts predictable, but it is better to express all criteria in one comparator with thenComparing.
Is Stream.concat of a parallel and a sequential stream parallel?
Yes, the result is parallel if either input is parallel. The result is ordered only if both inputs are ordered.
API reference
java.util.stream.Stream<T>
| Method | Description |
|---|---|
Stream<T> limit(long maxSize) | at most the first maxSize elements (short-circuiting) |
Stream<T> skip(long n) | all but the first n elements |
Stream<T> takeWhile(Predicate<? super T> predicate) (Java 9) | the longest prefix whose elements satisfy predicate |
Stream<T> dropWhile(Predicate<? super T> predicate) (Java 9) | the elements after that prefix |
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) | the elements of a followed by those of b |
Stream<T> distinct() | the elements without duplicates (by equals), first occurrences kept |
Stream<T> sorted(), Stream<T> sorted(Comparator<? super T> comparator) | the elements in sorted order; stable for ordered streams |
Stream<T> peek(Consumer<? super T> action) | the same elements, calling action on each as it is consumed |
Summary
limitandskipcut by position and combine into paging.skip(1)removes the leading empty string thatsplitproduces when the input starts with a delimiter.takeWhileanddropWhilesplit at the first element that fails the predicate, unlikefilter, which tests every element.takeWhilecan end an infinite stream.concatjoins two streams. For many streams, useStream.of(...).flatMap(s -> s).distinctusesequals.sortedis stable. Both are stateful, andsortedmust see the whole stream first.peekis for debugging only. It may not run at all, for example beforecount()on a stream of known size.
Practice Questions
What does Stream.iterate(1, n -> n + 1).filter(n -> n < 5).toList() do, and how do you fix it?
It never terminates. filter keeps testing elements forever because it can't know that no later number is below 5. Use takeWhile(n -> n < 5), which stops at the first failing element, or Stream.iterate(1, n -> n < 5, n -> n + 1).
Write a pipeline that returns the third page (page size 10) of a list of names sorted alphabetically.
names.stream().sorted().skip(20).limit(10).toList(). Skip the first two pages (20 elements), then take ten.
Why is Stream.generate(Math::random).sorted().limit(10).toList() a bug, while limit before sorted works?
sorted must receive every element before it can emit the first one, and the generated stream is infinite, so it never finishes. Stream.generate(Math::random).limit(10).sorted().toList() first cuts the stream to ten elements, then sorts them.
You use peek(list::add) to collect elements while calling count(). Sometimes the list stays empty. Why?
peek is only for debugging and isn't guaranteed to run. When the stream's size is known without traversing it, count() returns the size directly and skips the pipeline, so the peek action never executes. Collect elements with toList() or a collector instead.
Two records with equal fields appear in a stream. Does distinct() remove one of them? What about two objects of a class that doesn't override equals?
Records implement equals and hashCode by their components, so equal records are duplicates and only the first is kept. A class without its own equals inherits identity comparison from Object, so two separate objects always count as distinct, however similar their contents.
Previous: Java Stream filter, map, flatMap and mapMulti
Next: Java Stream Reductions: count, max, min, findFirst, findAny and anyMatch
Related reading
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.