associate and flatMap
- Kotlin course
- Intermediate
- Lesson 68/116
- 5 min
Learn transformation with associate and flatMap.
associate and flatMap
associate produces a Map from a list. Each element is turned into a key-value pair. Example: words.associate { it to it.length } maps each word to its length. The to infix function creates a Pair.
flatMap transforms each element into a collection and then merges those collections into a single flat list. Example: lists.flatMap { it } flattens nested lists. While map replaces each element with one value, flatMap replaces each element with multiple values and concatenates the results.
associate and flatMap examples
associateBy selects only the key; the value is the element itself. associateWith produces a value for each key. Example: words.associateWith { it.length } maps words to their lengths.
flatMap can also unfold a string into characters: words.flatMap { it.toList() } produces characters from each word and merges them into one list. flatten only flattens nested lists without transformation. flatMap equals map followed by flatten.
Practice Apply associate and flatMap
Define val words = listOf("apple", "pear", "cherry"). Produce a word-length Map with associate { it to it.length } and print it with println(lengths). Flatten all characters with flatMap { it.toList() } and print the count with println(chars.size).
Starter code
fun main() {
val words = listOf("apple", "pear", "cherry")
// Produce a Map with associate, flatten chars with flatMap, and print
}Sample solution
fun main() {
val words = listOf("apple", "pear", "cherry")
val lengths = words.associate { it to it.length }
val chars = words.flatMap { it.toList() }
println(lengths)
println(chars.size)
}Expected output
{apple=5, pear=4, cherry=6}
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match associate and flatMap
| Term | Meaning |
|---|---|
associate |
Produces Map |
flatMap |
Flattens |
{ it to it.length } |
Key-value |
List<List<T>> |
Nested list |
2 Complete the associate call
words.____ { it to it.length }
words.associate { it to it.length }
Explanation: associate produces a word-length Map.
3 What does flatMap return?
- A Set
- A nested list
- A Map
- A single flat list Correct answer
Explanation: flatMap turns each element into a collection and merges into one flat list.