Middle
What is the difference between map and flatMap operations?
sobes.tech AI
Answer from AI
map transforms each element of the stream into a new element, returning a stream with the same number of elements.
flatMap transforms each element of the stream into a stream of elements, and then flattens these nested streams into a single flat stream. It is used when the transformation of one element results in multiple elements.
Example:
Suppose we have a list of lists of strings: List<List<String>> listOfLists.
Using map:
// Transforms each list of strings into its size
listOfLists.stream()
.map(list -> list.size())
.forEach(System.out::println);
// Will print the size of each inner list: 2, 3, 1, etc.
Using flatMap:
// Transforms each list of strings into a stream of strings of that list
// and flattens (merges) them into a single stream of all strings
listOfLists.stream()
.flatMap(list -> list.stream())
.forEach(System.out::println);
// Will print all strings from all inner lists: "a", "b", "c", "d", "e"...
Comparison table:
| Operation | Input | Transformation | Output | Purpose |
|---|---|---|---|---|
map |
Stream<T> |
T -> R |
Stream<R> |
Transforming each element |
flatMap |
Stream<T> |
T -> Stream<R> |
Stream<R> |
Transforming each element into a stream and flattening |