Course contentsShow
← Java
Lesson 1443 of 2,87032. Streams API: Intermediate OperationsFree lesson

Multiple Levels of Nesting: Complex Flattening

Applying flatMap multiple times to flatten deeply nested structures.

Multiple Levels of Nesting: Complex Flattening

You'll learn how to flatten deeply nested structures by chaining multiple flatMap operations.

The Problem: Nested Upon Nested

Sometimes data isn't just one level deep—you might have lists of lists of lists, or objects containing collections that themselves contain collections. Imagine a library with shelves, where each shelf has boxes, and each box contains books. To get all the books, you need to "unwrap" multiple layers.

Chaining flatMap to Flatten Deep Structures

When you have multiple levels of nesting, you apply flatMap multiple times in sequence. Each flatMap peels away one layer of nesting, transforming the structure into a flatter stream.

List<List<List<String>>> deeplyNested = List.of(
    List.of(List.of("a", "b"), List.of("c")),
    List.of(List.of("d", "e", "f"))
);

// Flatten two levels: first from List<List<List>> to List<List>, 
// then from List<List> to List
List<String> flattened = deeplyNested.stream()
    .flatMap(Collection::stream)  // Removes outermost List
    .flatMap(Collection::stream)  // Removes next List layer
    .collect(Collectors.toList());

// Result: [a, b, c, d, e, f]

Each flatMap operation processes one nesting level, allowing you to drill down through complex structures systematically.

Real-World Example

class Department {
    List<Team> teams;
}

class Team {
    List<String> members;
}

// Get all members from all teams across all departments
List<Department> departments = // ...

List<String> allMembers = departments.stream()
    .flatMap(dept -> dept.teams.stream())      // Flatten departments to teams
    .flatMap(team -> team.members.stream())    // Flatten teams to members
    .collect(Collectors.toList());

Key Takeaway: Use multiple chained flatMap operations to flatten deeply nested structures—each flatMap removes one level of nesting, allowing you to work with complex hierarchies declaratively.