Java Stream Intermediate Operations: filter, map, flatMap, sorted, distinct, limit and peek (OCP 21)
Stream intermediate operations for the OCP 21 exam: filter, distinct, limit, skip, map, flatMap, concat, sorted with and without a Comparator, peek, takeWhile and dropWhile, how chained operations run, why sorted hangs on infinite streams, side effects, and checked exceptions in lambdas.
kvi5hnuCode Sprout team member7 min readOn this page
An intermediate operation takes a stream and returns a new stream. Because they're lazy (article 61), they also work on infinite streams: each step just passes elements along when they're requested.
![Rows of input tokens passing through an operation to output tokens: filter keeps 4 and 5 from 1,4,2,5; map multiplies by 10; flatMap turns lists [a], [], [b,c] into a, b, c; distinct removes repeated x; sorted orders c,a,b; limit(2) keeps the first two; skip(2) drops the first two; takeWhile keeps 1,3 until 8 fails; dropWhile drops until 8 and keeps 8,2](https://code-sprout-content.laxmi.solutions/asset/2026/11/czxbykw5rueqx7k7.png)
filter
Stream<T> filter(Predicate<? super T> predicate)
filter keeps the elements for which the predicate returns true. The lambda must return a boolean, so filter(s -> s.length()) doesn't compile.
distinct
Stream<T> distinct()
distinct removes duplicates using equals() (and hashCode). Duplicates don't have to be next to each other: Stream.of("duck", "duck", "goose", "duck").distinct() gives duck, goose. The first occurrence is kept. Records compare by value, so two equal record objects count as duplicates.
limit and skip
Stream<T> limit(long maxSize)
Stream<T> skip(long n)
limit(n)keeps at most the firstnelements. It short-circuits, which turns an infinite stream into a finite one.skip(n)drops the firstnelements. Skipping more elements than the stream has gives an empty stream, not an exception.
Stream.iterate(1, n -> n + 1).skip(5).limit(2).toList(); // [6, 7]
map
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
map transforms each element, one in, one out. The element type can change:
Stream<Integer> lengths = Stream.of("monkey", "ape").map(String::length); // 6, 3
Don't confuse it with the Map interface: stream map means "transform".
flatMap
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
flatMap transforms each element into a stream and then joins all those streams into one. It's one in, zero or more out. Use it to flatten nested structures:
List<List<String>> albums = List.of(List.of(), List.of("Ash"), List.of("Bloom", "Coral"));
albums.stream().flatMap(List::stream).toList(); // [Ash, Bloom, Coral]: the empty list disappears
The function must return a Stream. flatMap(String::length) doesn't compile, because it returns an int. To flatten into a primitive stream, use flatMapToInt and its relatives.
mapMulti (Java 16) is an alternative to flatMap for the same one-to-many job. It pushes results into a consumer instead of creating a small stream for each element: .<String>mapMulti((s, sink) -> { for (String p : s.split(",")) sink.accept(p); }).
concat
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)
concat is a static method of Stream, not an instance method. It returns all elements of a, then all elements of b. Mixed types are inferred to a common supertype, so Stream<String> r = Stream.concat(strings, Stream.of(1)) doesn't compile, but Stream<Object> r = … does.
sorted
Stream<T> sorted() // natural order: elements must be Comparable
Stream<T> sorted(Comparator<? super T> comparator)
Stream.of("pear-", "fig-").sorted(); // fig-, pear-
Stream.of("green tea-", "mint-").sorted(Comparator.reverseOrder()); // mint-, green tea-
Stream.of("a", "bb", "cc", "d").sorted(Comparator.comparing(String::length)); // a, d, bb, cc (stable)
There's a classic method-reference trap here:
stream.sorted(Comparator.reverseOrder()); // fine: calls the method, which returns a Comparator
stream.sorted(Comparator::reverseOrder); // DOES NOT COMPILE
Comparator::reverseOrder refers to a method that takes no arguments, so it fits a Supplier<Comparator>, not the Comparator that sorted needs. sorted(String::compareTo), on the other hand, compiles: an unbound reference takes two strings and returns an int.
sorted() on elements that don't implement Comparable compiles, but fails at run time with ClassCastException, just like TreeSet (article 56).
sorted is a stateful operation: it can't pass anything on until it has seen every element. On an infinite stream that never happens, so the program hangs, or eventually runs out of memory.
peek
Stream<T> peek(Consumer<? super T> action)
peek runs an action for each element as it passes and returns the stream unchanged. It's meant for debugging:
long count = Stream.of("black tea", "green tea", "mint")
.filter(s -> s.startsWith("m"))
.peek(System.out::println) // mint
.count(); // 1
peek takes a Consumer, so a lambda with a return value doesn't compile, while an expression lambda whose value is ignored (x -> x.length()) does. Being intermediate, peek does nothing without a terminal operation. Since Java 9, a pipeline may also skip peek entirely when it can compute the result without looking at the elements, for example List.of(1, 2).stream().peek(...).count(). So don't rely on peek for real work.
takeWhile and dropWhile (Java 9)
Stream<T> takeWhile(Predicate<? super T> p) // elements up to (not including) the first that fails
Stream<T> dropWhile(Predicate<? super T> p) // everything from the first element that fails onward
Unlike filter, these look at the beginning of the stream only:
List<Integer> temps = List.of(12, 15, 19, 24, 18, 11);
temps.stream().takeWhile(t -> t < 20).toList(); // [12, 15, 19] (18 and 11 are never examined)
temps.stream().dropWhile(t -> t < 20).toList(); // [24, 18, 11]
temps.stream().filter(t -> t < 20).toList(); // [12, 15, 19, 18, 11]
takeWhile can stop an infinite stream: Stream.iterate(1, n -> n + 1).takeWhile(n -> n < 4) gives [1, 2, 3].
How a chain of operations runs
List.of("Plum", "Kiwi", "Mango", "Pear").stream()
.filter(n -> n.length() < 5)
.sorted()
.limit(2)
.forEach(System.out::println); // Kiwi, Pear
Plum,KiwiandPearpass the filter one by one.Mangois dropped.sortedholds the three that passed.- When the source is exhausted,
sortedsorts and starts releasing elements:Kiwi, thenPear. - After two elements,
limitsignals that it's done, and the pipeline stops.
Order matters for infinite streams:
Stream.generate(() -> "Kiwi").filter(n -> n.length() < 5).sorted().limit(2)...; // hangs: sorted waits forever
Stream.generate(() -> "Kiwi").filter(n -> n.length() < 5).limit(2).sorted()...; // prints Kiwi twice
Stream.generate(() -> "Watermelon").filter(n -> n.length() < 5).limit(2)...; // hangs: limit never sees 2 elements
A pipeline can also feed another one. In Stream.of(...).filter(...).collect(Collectors.toList()).stream().count(), collect ends the first pipeline and .stream() starts a second. When you read such code, find each source and each terminal operation.
Side effects
Stream operations should transform data, not change things outside the stream. On the exam you'll see code that does both, so know what happens:
- Changing the source while the pipeline runs (from
peek,maporforEach) gives wrong results or aConcurrentModificationException. For example,Stream.of(numbers, letters).peek(l -> l.remove(0)).map(List::size)prints00instead of11. - Updating outside variables: a lambda can't change a local variable (it must be effectively final, article 51), but it can change a field. That compiles, but it's fragile, especially with parallel streams. Return the value from the stream instead, using
count,sumorcollect.
Checked exceptions in lambdas
The built-in functional interfaces (Function, Predicate, Supplier and so on) don't declare checked exceptions. So a method that throws one can't be used directly:
static String loadLyrics(String title) throws IOException { ... }
stream.map(Solution::loadLyrics); // DOES NOT COMPILE: unreported IOException
Supplier<List<String>> s = Library::create; // DOES NOT COMPILE if create() throws IOException
You have two options:
- Catch the exception inside the lambda, or in a helper method, and rethrow it as an unchecked exception.
UncheckedIOExceptionexists for exactly this. - Use a functional interface that allows checked exceptions, such as
java.util.concurrent.Callable(call() throws Exception), when the API you're calling accepts one.
static String loadLyricsUnchecked(String title) {
try { return loadLyrics(title); }
catch (IOException e) { throw new UncheckedIOException(e); }
}
stream.map(Solution::loadLyricsUnchecked); // compiles
Throwing an unchecked exception from a lambda is always allowed.
What's current
takeWhileanddropWhile(Java 9) andmapMulti(Java 16) are current methods and can appear on 1Z0-830.- Java 24 finalized stream gatherers (
Stream.gatherwithGatherers.windowFixed,windowSliding,fold,scanandmapConcurrent). They let you write custom intermediate operations. They're not on 1Z0-830.
Exam traps from this article
A complete example
The program builds a small playlist and applies every intermediate operation: distinct, filter, map, sorted with and without a comparator, skip/limit, flatMap, concat, takeWhile/dropWhile. It traces the processing order with peek, makes an infinite source safe by limiting before sorting, and wraps a checked exception for use inside map.
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
public class Solution {
record Track(String title, String artist, int seconds) {}
static final List<Track> PLAYLIST = List.of(
new Track("Tidal", "Nova", 214),
new Track("Ember", "Kite", 187),
new Track("Tidal", "Nova", 214), // duplicate record: equal by value
new Track("Quartz", "Lumen", 302),
new Track("Drift", "Kite", 245));
// A method that throws a checked exception can't be used directly in map()
static String loadLyrics(String title) throws IOException {
if (title.startsWith("Q")) throw new IOException("no lyrics for " + title);
return title.toLowerCase() + ".txt";
}
static String loadLyricsUnchecked(String title) {
try {
return loadLyrics(title);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static void main(String[] args) {
// filter + distinct + map
List<String> longTitles = PLAYLIST.stream()
.distinct() // uses equals(): the second Tidal goes
.filter(t -> t.seconds() > 200)
.map(Track::title)
.toList();
System.out.println("distinct, over 200s: " + longTitles);
// sorted with and without a Comparator, then skip/limit
System.out.println("natural order of artists: "
+ PLAYLIST.stream().map(Track::artist).distinct().sorted().toList());
System.out.println("2nd and 3rd longest: "
+ PLAYLIST.stream().distinct()
.sorted(Comparator.comparingInt(Track::seconds).reversed())
.skip(1).limit(2).map(Track::title).toList());
// flatMap: one-to-many
List<List<String>> albums = List.of(List.of(), List.of("Ash"), List.of("Bloom", "Coral"));
System.out.println("flatMap: " + albums.stream().flatMap(List::stream).toList()
+ ", letters: " + Stream.of("hi", "yo").flatMap(w -> w.chars().mapToObj(c -> (char) c)).toList());
// concat
System.out.println("concat: " + Stream.concat(Stream.of("intro"), Stream.of("outro", "bonus")).toList());
// takeWhile / dropWhile (Java 9) on an ordered stream
List<Integer> temps = List.of(12, 15, 19, 24, 18, 11);
System.out.println("takeWhile < 20: " + temps.stream().takeWhile(t -> t < 20).toList()
+ ", dropWhile < 20: " + temps.stream().dropWhile(t -> t < 20).toList());
// peek shows the order of work: elements flow one by one, sorted() waits for all
System.out.print("trace: ");
Stream.of("c", "a", "b")
.peek(s -> System.out.print("in:" + s + " "))
.sorted()
.peek(s -> System.out.print("sorted:" + s + " "))
.limit(2)
.forEach(s -> System.out.print("out:" + s + " "));
System.out.println();
// limit before sorted makes an infinite source safe
System.out.println("generate -> limit -> sorted: "
+ Stream.generate(() -> "echo").limit(2).sorted().toList());
// Checked exceptions: wrap them in an unchecked exception
try {
PLAYLIST.stream().map(Track::title).map(Solution::loadLyricsUnchecked).forEach(f -> System.out.print(f + " "));
} catch (UncheckedIOException e) {
System.out.println("| stopped: " + e.getCause().getMessage());
}
}
}
Output:
distinct, over 200s: [Tidal, Quartz, Drift]
natural order of artists: [Kite, Lumen, Nova]
2nd and 3rd longest: [Drift, Tidal]
flatMap: [Ash, Bloom, Coral], letters: [h, i, y, o]
concat: [intro, outro, bonus]
takeWhile < 20: [12, 15, 19], dropWhile < 20: [24, 18, 11]
trace: in:c in:a in:b sorted:a out:a sorted:b out:b
generate -> limit -> sorted: [echo, echo]
tidal.txt ember.txt tidal.txt | stopped: no lyrics for Quartz
Points to notice:
distinct()removed the secondTidaltrack because records with equal components areequals.skip(1).limit(2)after the descending sort picked the 2nd and 3rd longest tracks:Drift(245 seconds) andTidal(214).Quartz(302) was skipped.takeWhilestopped at 24, whiledropWhilekept everything from 24 on, including 18 and 11.- The trace shows all three
in:messages before anysorted:message. After two outputs,limitstopped the pipeline, socwas never released bysorted. - The checked
IOExceptionwas wrapped in anUncheckedIOException. It stopped the pipeline whenQuartzcame along, after three files had already been printed.
Common questions
Is peek the same as forEach?
They take the same Consumer, but peek is intermediate: it returns the stream and runs only when a terminal operation pulls elements. forEach is terminal.
Does the order of filter and map matter?
For the result, sometimes. For performance, filtering first means fewer elements get mapped. With limit and sorted, order can decide whether the program finishes at all.
flatMap or mapMulti?
flatMap is the classic and the one the exam uses. mapMulti avoids creating many tiny streams, which helps when each element produces just a few results.
Summary
filterkeeps matches,distinctdropsequalsduplicates,limit/skipcut by position, andtakeWhile/dropWhilecut by the first failing element.maptransforms one-to-one,flatMapone-to-many and flattens, andStream.concatjoins two streams.sorted()uses natural order andsorted(Comparator)a custom one. It's stateful and never finishes on an infinite stream.peekis for debugging. Avoid side effects, especially changes to the source.- Checked exceptions must be handled inside lambdas, or wrapped in unchecked ones such as
UncheckedIOException.
Practice quiz
Test yourself with the intermediate operations quiz: 10 exam-style questions with explanations.
Previous: Java Stream Terminal Operations: count, min, max, find, match, forEach, reduce and collect (OCP 21)
Next: Java Primitive Streams: IntStream, LongStream, DoubleStream and Summary Statistics (OCP 21)
Related reading
- Java Stream Terminal Operations: count, min, max, find, match, forEach, reduce and collect (OCP 21)
- Java Streams: Pipeline Flow and Creating Finite and Infinite Streams (OCP 21)
- Java Optional: Creating, Checking and Unwrapping Optional Values (OCP 21)
- Java Lambda Variables: Parameters, Locals and Effectively Final Captures (OCP 21)
- Java Functional Interface Convenience Methods and Primitive Specializations (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.