00:00

Problem Statement

Input/Output Examples

Visual Explanation

With map(List::stream) the result would be a Stream<Stream<Integer>>. flatMap() removes that extra level, so a normal collect() gives a flat list.

Approaches

The stream version flattens in one pipeline. The loop version does the same with addAll().

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the total number of elements across all inner lists. Each element is copied once into the result.

Interview Tips and Recommended Approach

  • Explain map() versus flatMap(). map() is one-to-one; flatMap() is one-to-many and flattens.
  • Use it beyond lists. flatMap() also flattens arrays (Arrays::stream) and Optional values.
  • Know it handles empty inner lists without any special code.
  • Flatten deeper nesting by applying flatMap() once per level.

Recommended Approach: flatMap(List::stream)

Why: it states the intent, "flatten", directly and works for any nesting of collections with one method reference.