Java Stream filter, map, flatMap and mapMulti
The core Java stream transformations: filter keeps elements, map transforms them, flatMap flattens nested results and mapMulti pushes zero or more results without inner streams. Includes grapheme clusters, dropping nulls with ofNullable, and the primitive mapToInt and flatMapToInt.
kvi5hnuCode Sprout team member9 min readOn this page
A stream transformation is an intermediate operation that produces a new stream whose elements are derived from the elements of another stream. Three transformations do most of the work in everyday code: filter decides which elements stay, map decides what each element becomes, and flatMap handles the case where one element turns into several. Java 16 added a fourth, mapMulti, which does the same job as flatMap without building small streams. This article covers all four and when to choose which.
filter: keep the elements that match
filter takes a Predicate<? super T>, a function from an element to boolean, and keeps exactly the elements for which it returns true:
Stream<String> longWords = wordList.stream().filter(w -> w.length() > 12);
The element type doesn't change. A Stream<String> stays a Stream<String>, possibly with fewer elements. To filter by the negation of an existing predicate, Predicate.not reads nicely: filter(Predicate.not(String::isBlank)).
map: transform every element
map takes a Function<? super T, ? extends R> and applies it to each element. The result is a stream of the returned values, in the same order, and its element type is whatever the function returns:
Stream<String> lowercaseWords = words.stream().map(String::toLowerCase); // String → String
Stream<Character> firstCodeUnits = words.stream().map(s -> s.charAt(0)); // String → Character
Stream<Integer> lengths = words.stream().map(String::length); // String → Integer
A method reference like String::toLowerCase is often clearer than the equivalent lambda s -> s.toLowerCase(). map always produces exactly one output element per input element. If you want to drop some, combine it with filter.
flatMap: when each element becomes several
Suppose a function returns a stream for each element. Here is one that splits a string into its grapheme clusters, the characters a user perceives on the screen:
static Stream<String> graphemeClusters(String s) {
return Stream.of(s.split("\\b{g}")); // \b{g} is a grapheme cluster boundary (Java 9)
}
Why not just split into char values? Because a char is a UTF-16 code unit, and many characters need more than one. The pirate flag 🏴☠️ is built from four code points (black flag, zero-width joiner, skull and crossbones, variation selector) stored in five char values. It's still a single grapheme cluster, the unit you'd want when reversing or truncating text for display. The first course discussed code units and code points; grapheme clusters are the next level up.
Now apply this function with map:
Stream<Stream<String>> result = words.stream().map(w -> graphemeClusters(w));
You get a stream of streams: [["R", "o", "w"], ["y", "o", "u", "r"], …]. Usually you want one flat stream of all the clusters instead. That's what flatMap does. It calls the function on each element and concatenates the resulting streams in order:
Stream<String> flatResult = words.stream().flatMap(w -> graphemeClusters(w));
// ["R", "o", "w", "y", "o", "u", "r", ...]

The rule of thumb: if your function returns a Stream, you almost certainly want flatMap, not map. The same idea, "apply, then flatten", appears for Optional (article 7) and for CompletableFuture.thenCompose in the first course. It's a general pattern that functional programmers call monadic bind.
Typical uses of flatMap
- One-to-many relationships. Every order has a list of items.
orders.stream().flatMap(o -> o.items().stream())gives one stream of all items. An order with no items simply contributes nothing. - Dropping missing values. Combined with
Stream.ofNullable, a function that may returnnullbecomes a function that returns zero or one elements:countries.flatMap(c -> Stream.ofNullable(capitals.get(c)))silently skips countries without a capital. - Expanding lines into words.
lines.flatMap(line -> Arrays.stream(line.split(" "))).
flatMapToInt, flatMapToLong and flatMapToDouble flatten into primitive streams. For example, Stream.of("2025", "11").flatMapToInt(String::chars) gives an IntStream of all the characters.
mapMulti: flatMap without the inner streams
flatMap asks your function to return a stream for each element. When most elements produce zero, one or two results, building all those little streams is wasteful, and the code to build them can be awkward. mapMulti (Java 16) turns it around. Your function receives the element together with a consumer, and it calls the consumer's accept method once for every result it wants to emit:
Stream<String> result = words.stream().<String>mapMulti((s, sink) -> {
iter.setText(s); // iter is a BreakIterator.getCharacterInstance()
int start = iter.first();
int end = iter.next();
while (end != BreakIterator.DONE) {
sink.accept(s.substring(start, end)); // emit one grapheme cluster
start = end;
end = iter.next();
}
});
BreakIterator (covered with internationalization in Part 7) finds the same grapheme cluster boundaries as \b{g}, but it hands them out one at a time, which fits mapMulti perfectly. There's no intermediate stream or array.
Two more patterns where mapMulti shines:
// filter and map in one step
Stream.of(1, 2, 3, 4, 5, 6).<Integer>mapMulti((n, sink) -> { if (n % 2 == 0) sink.accept(n * n); })
// keep only the elements of one type, already cast
objects.stream().<String>mapMulti((o, sink) -> { if (o instanceof String s) sink.accept(s); })
Which should you use? Prefer flatMap when you already have a stream or collection for each element, as in o.items().stream(). Prefer mapMulti when you generate results in a loop or with conditions, or when each element yields only a few results.
A complete example
import java.text.BreakIterator;
import java.util.*;
import java.util.stream.*;
public class Solution {
// split a string into user-perceived characters (grapheme clusters)
static Stream<String> graphemeClusters(String s) {
return Stream.of(s.split("\\b{g}"));
}
public static void main(String[] args) {
List<String> words = List.of("Row", "your", "boat", "gently", "down", "the", "stream");
// filter: keep some elements
System.out.println("filter: " + words.stream().filter(w -> w.length() > 4).toList());
// map: transform every element
System.out.println("map: " + words.stream().map(String::toUpperCase).toList());
System.out.println("map: " + words.stream().map(w -> w.charAt(0)).toList());
System.out.println("map: " + words.stream().map(String::length).toList());
// map with a stream-valued function gives a stream of streams
Stream<Stream<String>> nested = words.stream().limit(2).map(Solution::graphemeClusters);
System.out.println("nested: " + nested.map(Stream::toList).toList());
// flatMap flattens the results into one stream
System.out.println("flatMap: " + words.stream().limit(2).flatMap(Solution::graphemeClusters).toList());
// why grapheme clusters? chars and code points can split a "character"
String pirate = "Ahoy 🏴☠️";
System.out.println("length() in char values: " + pirate.length());
System.out.println("code points: " + pirate.codePoints().count());
System.out.println("graphemes: " + graphemeClusters(pirate).toList());
// flatMap with ofNullable drops nulls produced along the way
Map<String, String> capitals = Map.of("France", "Paris", "Japan", "Tokyo");
List<String> found = Stream.of("Japan", "Atlantis", "France")
.flatMap(country -> Stream.ofNullable(capitals.get(country)))
.toList();
System.out.println("capitals found: " + found);
// flatMap from objects to their parts
record Order(String customer, List<String> items) {}
List<Order> orders = List.of(
new Order("Ada", List.of("pen", "ink")),
new Order("Linus", List.of()),
new Order("Grace", List.of("tape", "pen", "chip")));
System.out.println("all items: " + orders.stream().flatMap(o -> o.items().stream()).toList());
System.out.println("distinct items: " + orders.stream()
.flatMap(o -> o.items().stream()).distinct().sorted().toList());
// mapMulti: push zero or more results into a consumer, no inner stream needed
BreakIterator iter = BreakIterator.getCharacterInstance();
List<String> clusters = words.stream().limit(2).<String>mapMulti((s, sink) -> {
iter.setText(s);
int start = iter.first();
int end = iter.next();
while (end != BreakIterator.DONE) {
sink.accept(s.substring(start, end));
start = end;
end = iter.next();
}
}).toList();
System.out.println("mapMulti: " + clusters);
// mapMulti as a combined filter and map
List<Integer> evenSquares = Stream.of(1, 2, 3, 4, 5, 6)
.<Integer>mapMulti((n, sink) -> { if (n % 2 == 0) sink.accept(n * n); })
.toList();
System.out.println("even squares: " + evenSquares);
// mapMulti for type-based filtering and casting
List<Object> mixed = List.of(1, "two", 3.0, "four", 5);
List<String> strings = mixed.stream()
.<String>mapMulti((o, sink) -> { if (o instanceof String s) sink.accept(s); })
.toList();
System.out.println("strings only: " + strings);
// the primitive variants avoid boxing
int totalLetters = words.stream().mapToInt(String::length).sum();
System.out.println("total letters: " + totalLetters);
int[] digits = Stream.of("2025", "11", "14")
.flatMapToInt(String::chars)
.map(c -> c - '0')
.toArray();
System.out.println("digits: " + Arrays.toString(digits));
}
}
filter: [gently, stream]
map: [ROW, YOUR, BOAT, GENTLY, DOWN, THE, STREAM]
map: [R, y, b, g, d, t, s]
map: [3, 4, 4, 6, 4, 3, 6]
nested: [[R, o, w], [y, o, u, r]]
flatMap: [R, o, w, y, o, u, r]
length() in char values: 10
code points: 9
graphemes: [A, h, o, y, , 🏴☠️]
capitals found: [Tokyo, Paris]
all items: [pen, ink, tape, pen, chip]
distinct items: [chip, ink, pen, tape]
mapMulti: [R, o, w, y, o, u, r]
even squares: [4, 16, 36]
strings only: [two, four]
total letters: 30
digits: [2, 0, 2, 5, 1, 1, 1, 4]
Note that "Ahoy 🏴☠️".length() is 10 and there are 9 code points, yet only six grapheme clusters. The flag occupies five char values and four code points, but it's one character to the reader.
Common questions
What happens if the function in map returns null?
The stream then contains a null element; map does not filter it out. If null means "no result", use flatMap with Stream.ofNullable, or mapMulti and simply do not call the consumer.
And if the function in flatMap returns null instead of a stream?
flatMap treats a null result as an empty stream, but returning Stream.empty() is clearer. flatMap also closes each inner stream after copying its elements, so a function may safely return a stream that holds a resource, such as Files.lines(path).
Is flatMap lazy?
Yes, since Java 10. Earlier versions consumed each inner stream completely, so flatMap combined with findFirst over an infinite inner stream never finished. On current Java, Stream.iterate(1, x -> x + 1).flatMap(x -> Stream.iterate(x, y -> y + 1)).findFirst() returns at once.
How do I call a method that throws a checked exception inside map?
Lambdas passed to stream operations cannot throw checked exceptions. Wrap the call in a helper that catches the exception and rethrows an unchecked one, such as UncheckedIOException for an IOException. Then catch it around the terminal operation if needed. If many elements can fail and you want to continue, map to a result type, for example a record with a value or an error, instead of throwing.
Is filter(a).filter(b) slower than filter(a.and(b))?
Hardly. Elements flow through both filters in a single pass, and the JIT compiler inlines small lambdas. Choose whichever reads better. Separate filters are often clearer.
Should I use a method reference or a lambda?
Use whichever is clearer. map(String::trim) is shorter than map(s -> s.trim()), but map(s -> s.substring(0, 3)) cannot be written as a method reference. The compiled code is about the same.
API reference
java.util.stream.Stream<T>
| Method | Description |
|---|---|
Stream<T> filter(Predicate<? super T> predicate) | the elements that satisfy predicate |
<R> Stream<R> map(Function<? super T, ? extends R> mapper) | the results of applying mapper to each element |
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) | the concatenation of the streams that mapper returns |
<R> Stream<R> mapMulti(BiConsumer<? super T, ? super Consumer<R>> mapper) (Java 16) | every value that mapper passes to the consumer, for each element in turn |
IntStream mapToInt(ToIntFunction<? super T> mapper), also mapToLong, mapToDouble | a primitive stream of the results |
IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper), also …ToLong, …ToDouble | flattens into a primitive stream |
IntStream mapMultiToInt(BiConsumer<? super T, ? super IntConsumer> mapper) (Java 16), also …ToLong, …ToDouble | mapMulti into a primitive stream |
java.util.function.Predicate<T>
| Method | Description |
|---|---|
static <T> Predicate<T> not(Predicate<? super T> target) (Java 11) | the negation of target |
Summary
filterkeeps the elements that satisfy a predicate. The element type stays the same.maptransforms each element into exactly one result, possibly of a different type. UsemapToIntand friends to avoid boxing.flatMapis for functions that return streams. It concatenates the results into one flat stream. Combined withStream.ofNullable, it dropsnullresults.mapMultilets a function emit any number of results through a consumer, avoiding small intermediate streams. Give it a type witness like<String>mapMulti.- Grapheme clusters (
\b{g},BreakIterator) are the right unit for user-visible characters, notcharvalues or even code points.
Practice Questions
What is the type of Stream.of("a b", "c").map(s -> Arrays.stream(s.split(" ")))? How do you get a Stream<String> of the words?
It's a Stream<Stream<String>>, a stream with two inner streams. Replace map with flatMap: Stream.of("a b", "c").flatMap(s -> Arrays.stream(s.split(" "))) yields "a", "b", "c".
How can you look up a list of keys in a map and keep only the values that exist, in one pipeline?
keys.stream().flatMap(k -> Stream.ofNullable(map.get(k))). For a missing key, get returns null and ofNullable turns it into an empty stream, which contributes nothing. Alternatively, keys.stream().filter(map::containsKey).map(map::get), which does two lookups per key.
Why does List<String> s = objects.stream().mapMulti((o, sink) -> { if (o instanceof String str) sink.accept(str); }).toList(); fail to compile?
The compiler can't infer mapMulti's result type from the lambda, so it infers Object and the stream becomes a Stream<Object>. Write .<String>mapMulti(...) to fix the type.
You need the total number of characters in a list of words. Why is mapToInt(String::length).sum() better than map(String::length).reduce(0, Integer::sum)?
mapToInt produces an IntStream of primitive int values, so no Integer objects are created, and sum() reads clearly. The map version boxes every length and unboxes it again during the reduction.
Why can splitting "Ahoy 🏴☠️" into char values give the wrong result for a "reverse the characters" feature?
The flag is made of several code points stored in five char values. Reversing the char values separates and reorders them, breaking the surrogate pairs and the joiner sequence, so the flag turns into garbage. Splitting into grapheme clusters (\b{g} or BreakIterator) keeps the flag together.
Previous: Creating Java Streams: of, generate, iterate, ofNullable and More
Next: Java Stream limit, skip, takeWhile, concat, distinct, sorted and peek
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.