Java Stream API Program · OT20
Flatten a List of Lists Using flatMap() in Java
map() turns each list into one stream, giving a stream of streams. flatMap() joins those streams into one, which is exactly what flattening means.
Problem Statement
Given a list of lists of integers, return a single list containing all the numbers in order: the first inner list, then the second, and so on.
Inner lists may be empty, and the outer list may be empty too.
Input/Output Examples
[[1, 2], [3], [], [4, 5, 6]]Output[1, 2, 3, 4, 5, 6]Explanation: the empty list simply contributes nothing.[]Output[]Explanation: there is nothing to flatten.[[7], [7, 8]]Output[7, 7, 8]Explanation: flattening does not remove duplicates.Visual Explanation
- Inputlists[1, 2][3][][4, 5, 6]a stream of 4 lists
- flatMapstreams1 23—4 5 6List::stream on each
- Joinedstream123456one stream of 6 numbers
- collect[1, 2, 3, 4, 5, 6]
flatMap(List::stream) turns each inner list into a stream (purple) and joins them, in order, into one stream of numbers.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().
Approach 1: flatMap(List::stream) (Recommended)
Idea: stream the outer list, replace each inner list with its stream using flatMap(), and collect.
- Call
nested.stream(). - Apply
flatMap(List::stream). - Collect with
Collectors.toList().
Time: O(n) · Space: O(n). n is the total number of elements.
Approach 2: Loop With addAll()
Idea: append every inner list to one result list.
- Create an empty
ArrayList. - For each inner list, call
addAll(). - Return the result.
Time: O(n) · Space: O(n).
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.
Approach 1: flatMap(List::stream) (Recommended)
On Java 16 and later, .toList() can replace collect(Collectors.toList()), but it returns an unmodifiable list.
import java.util.List;
import java.util.stream.Collectors;
public class FlattenFlatMap {
// flatMap() turns each inner list into a stream and joins all those streams into one
static List<Integer> flatten(List<List<Integer>> nested) {
return nested.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
}
public static void main(String[] args) {
List<List<List<Integer>>> inputs = List.of(
List.of(List.of(1, 2), List.of(3), List.of(), List.of(4, 5, 6)),
List.of(),
List.of(List.of(7), List.of(7, 8)));
for (List<List<Integer>> nested : inputs) {
System.out.println(nested + " -> " + flatten(nested));
}
}
}
[[1, 2], [3], [], [4, 5, 6]] -> [1, 2, 3, 4, 5, 6] [] -> [] [[7], [7, 8]] -> [7, 7, 8]
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Loop With addAll()
Simple and slightly faster, and a useful comparison when explaining what flatMap() does.
import java.util.ArrayList;
import java.util.List;
public class FlattenLoop {
// The classic loop: append every inner list to one result list
static List<Integer> flatten(List<List<Integer>> nested) {
List<Integer> result = new ArrayList<>();
for (List<Integer> inner : nested) {
result.addAll(inner);
}
return result;
}
public static void main(String[] args) {
List<List<List<Integer>>> inputs = List.of(
List.of(List.of(1, 2), List.of(3), List.of(), List.of(4, 5, 6)),
List.of(),
List.of(List.of(7), List.of(7, 8)));
for (List<List<Integer>> nested : inputs) {
System.out.println(nested + " -> " + flatten(nested));
}
}
}
[[1, 2], [3], [], [4, 5, 6]] -> [1, 2, 3, 4, 5, 6] [] -> [] [[7], [7, 8]] -> [7, 7, 8]
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| flatMap(List::stream) | O(n) | O(n) |
| Loop With addAll() | O(n) | O(n) |
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()versusflatMap().map()is one-to-one;flatMap()is one-to-many and flattens. - Use it beyond lists.
flatMap()also flattens arrays (Arrays::stream) andOptionalvalues. - 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.