Java

flatMap — Flatten Nested Streams

admin by @admin ADMIN
Jun 12, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Map each element to a Stream, then concatenate all of them into one. Used everywhere from "all words from a list of sentences" to "all permissions from a list of roles".
Java
Raw
import java.util.*;
import java.util.stream.*;

class Demo {
    record User(String name, List<String> roles) {}

    void example() {
        var phrases = List.of("hello world", "foo bar baz", "java rocks");

        // Split each phrase into words, then flatten
        List<String> allWords = phrases.stream()
            .flatMap(s -> Arrays.stream(s.split(" ")))
            .toList();
        System.out.println(allWords);
        // [hello, world, foo, bar, baz, java, rocks]

        // All distinct roles across all users
        var users = List.of(
            new User("Alice", List.of("admin", "editor")),
            new User("Bob",   List.of("editor", "viewer")),
            new User("Cara",  List.of("admin"))
        );
        Set<String> roles = users.stream()
            .flatMap(u -> u.roles().stream())
            .collect(Collectors.toSet());
        System.out.println(roles);          // [admin, editor, viewer]

        // Optional<T> as Stream<T> via Optional::stream — common with flatMap
        Optional<String> opt = Optional.of("hello");
        String joined = Stream.of(opt, Optional.<String>empty(), Optional.of("world"))
            .flatMap(Optional::stream)
            .collect(Collectors.joining(" "));
        System.out.println(joined);          // hello world
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.