Problem Statement
Explain the difference between map, flatMap, and flatten with examples of when to use each.
Explanation
The map function transforms each element to a new value creating a new collection of the same size, like transforming list of names to their lengths. Use map when you have a one-to-one transformation where each input element produces exactly one output element.
FlatMap transforms each element into a collection and then flattens the result into a single collection, useful when each element maps to multiple values like expanding each word into its characters. It's equivalent to calling map then flatten, combining transformation and flattening in one step.
The flatten function only flattens nested collections without transformation, taking a collection of collections and returning a single flat collection. Use it when you already have nested collections and just need to flatten them without any element transformation.
Example: map turns listOf 1 2 3 with times 2 into listOf 2 4 6, flatMap turns listOf abc def with chars into flat list of all characters, and flatten turns listOf listOf 1 2 listOf 3 4 into listOf 1 2 3 4.
Practice Sets
This question appears in the following practice sets:
