flatMap() is an intermediate Stream operation that transforms each element into its own stream and then merges all those streams into a single, flattened stream.
Key Points: • Unlike map(), which produces a Stream<Stream<T>> for nested collections, flatMap() flattens the result into a single Stream<T>. • The mapping function must return a Stream, so for a List<List<Integer>>, you pass List::stream as the mapper. • It's the standard way to work with nested collections, optional values, or any structure that needs "unwrapping" during stream processing. • flatMap() can also be used to expand a single element into multiple elements, not just to flatten existing nested structures. • Combined with distinct() or collect(), it's common for merging and deduplicating values from multiple sub-lists.
Example: Given a list of lists like [[1, 2], [3, 4, 5]], flatMap(List::stream) merges them into one flat stream containing 1, 2, 3, 4, 5.
Code Example:
List<List<Integer>> nestedNumbers = Arrays.asList(
Arrays.asList(1, 2), Arrays.asList(3, 4, 5));
List<Integer> flatList = nestedNumbers.stream()
.flatMap(List::stream)
.collect(Collectors.toList());Interview Tip: A concise interview answer is:
"flatMap() converts each element into its own stream and merges all of them into one flattened stream, which is exactly what I need for a List<List<Integer>> - flatMap(List::stream) turns the nested lists into a single flat stream of integers, unlike map(), which would leave it nested."