Bird
Raised Fist0
Kotlinprogramming~10 mins

FlatMap for nested collections in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - FlatMap for nested collections
Start with nested list
↓
Apply flatMap
↓
For each inner list: extract elements
↓
Combine all elements into one list
↓
Return flattened list
↓
End
FlatMap takes each inner collection, extracts its elements, and combines them into one flat list.
Execution Sample
Kotlin
val nested = listOf(listOf(1, 2), listOf(3, 4))
val flat = nested.flatMap { it }
println(flat)
This code flattens a list of lists into a single list of elements.
Execution Table
StepActionInputOutputNotes
1Start with nested listlistOf(listOf(1, 2), listOf(3, 4))Same nested listInitial nested list with two inner lists
2Apply flatMapnested listProcess each inner listflatMap starts processing each inner list
3Extract elements from first inner listlistOf(1, 2)1, 2First inner list elements extracted
4Extract elements from second inner listlistOf(3, 4)3, 4Second inner list elements extracted
5Combine all elements1, 2, 3, 4listOf(1, 2, 3, 4)All elements combined into one list
6Print resultlistOf(1, 2, 3, 4)[1, 2, 3, 4]Final flattened list output
💡 All inner lists processed and combined into one flat list
Variable Tracker
VariableStartAfter Step 3After Step 4Final
nestedlistOf(listOf(1, 2), listOf(3, 4))SameSameSame
flatundefinedlistOf(1, 2)listOf(1, 2, 3, 4)listOf(1, 2, 3, 4)
Key Moments - 2 Insights
Why does flatMap return a single list instead of a list of lists?
Because flatMap extracts elements from each inner list and combines them into one list, as shown in steps 3, 4, and 5 of the execution_table.
What is the difference between map and flatMap here?
map would keep the inner lists nested (list of lists), but flatMap flattens them into a single list by combining all elements, as seen in the output of step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output after extracting elements from the first inner list (Step 3)?
AlistOf(1, 2)
BlistOf(3, 4)
C[1, 2, 3, 4]
DlistOf(listOf(1, 2), listOf(3, 4))
💡 Hint
Check the Output column in Step 3 of the execution_table.
At which step does the combined flat list get created?
AStep 4
BStep 5
CStep 2
DStep 6
💡 Hint
Look for the step where all elements are combined into one list in the execution_table.
If we replaced flatMap with map, what would the output look like?
AA single flat list of all elements
BAn empty list
CA list of lists, same as the original nested list
DA list with duplicated elements
💡 Hint
Recall the difference between map and flatMap explained in key_moments.
Concept Snapshot
flatMap takes a nested collection and flattens it into a single list.
Syntax: collection.flatMap { innerList -> innerList }
It extracts elements from each inner collection and combines them.
Use flatMap to avoid nested lists when you want a single list of all elements.
map keeps the nested structure; flatMap flattens it.
Full Transcript
This visual trace shows how Kotlin's flatMap works on nested collections. We start with a list of lists: [[1, 2], [3, 4]]. FlatMap processes each inner list, extracting elements one by one. First, it extracts 1 and 2 from the first inner list, then 3 and 4 from the second. It then combines all these elements into a single flat list: [1, 2, 3, 4]. The variable 'flat' holds this combined list. The key difference from map is that flatMap flattens the nested structure into one list, while map would keep the nested lists intact. This step-by-step execution helps beginners see how flatMap transforms nested collections into flat ones.

Practice

(1/5)
1. What does the flatMap function do when applied to a nested list in Kotlin?
easy
A. It filters elements based on a condition.
B. It sorts the nested lists in ascending order.
C. It transforms each element and flattens the result into a single list.
D. It converts the list into a set to remove duplicates.

Solution

  1. Step 1: Understand flatMap behavior

    flatMap applies a transformation to each element and then flattens the nested results into one list.
  2. Step 2: Compare with other functions

    Unlike sorting, filtering, or converting to a set, flatMap combines mapping and flattening in one step.
  3. Final Answer:

    It transforms each element and flattens the result into a single list. -> Option C
  4. Quick Check:

    flatMap = transform + flatten [OK]
Hint: Remember: flatMap = map + flatten in one step [OK]
Common Mistakes:
  • Confusing flatMap with filter or sort
  • Thinking flatMap removes duplicates
  • Assuming flatMap only maps without flattening
2. Which of the following is the correct syntax to use flatMap on a list of lists named nestedList in Kotlin?
easy
A. nestedList.flatMap { it }
B. nestedList.flatMap()
C. nestedList.flatMap -> it
D. nestedList.flatMap { it.flatten() }

Solution

  1. Step 1: Identify correct lambda syntax

    The flatMap function requires a lambda to transform each element. { it } returns each inner list as is.
  2. Step 2: Check other options

    nestedList.flatMap() misses lambda, C uses wrong arrow syntax, D uses flatten() incorrectly on flat inner lists.
  3. Final Answer:

    nestedList.flatMap { it } -> Option A
  4. Quick Check:

    flatMap needs a lambda like { it } [OK]
Hint: flatMap always needs a lambda block { } [OK]
Common Mistakes:
  • Omitting the lambda block
  • Using arrow (->) instead of curly braces
  • Using flatten() instead of identity mapping
3. What is the output of the following Kotlin code?
val nested = listOf(listOf(1, 2), listOf(3, 4))
val result = nested.flatMap { it.map { it * 2 } }
println(result)
medium
A. [[2, 4], [6, 8]]
B. [1, 2, 3, 4]
C. [2, 4, [6, 8]]
D. [2, 4, 6, 8]

Solution

  1. Step 1: Understand inner map transformation

    Each inner list element is multiplied by 2, so listOf(1,2) becomes listOf(2,4), and listOf(3,4) becomes listOf(6,8).
  2. Step 2: Apply flatMap flattening

    flatMap flattens the transformed lists into one list: [2, 4, 6, 8].
  3. Final Answer:

    [2, 4, 6, 8] -> Option D
  4. Quick Check:

    flatMap + map doubles and flattens [OK]
Hint: flatMap flattens after map transformation [OK]
Common Mistakes:
  • Expecting nested lists instead of flat list
  • Ignoring the inner map multiplication
  • Confusing output with original nested list
4. Identify the error in this Kotlin code snippet using flatMap:
val nested = listOf(listOf(1, 2), listOf(3, 4))
val result = nested.flatMap { it * 2 }
println(result)
medium
A. flatMap requires a filter inside the lambda.
B. Cannot multiply a list by an integer directly.
C. The variable 'nested' is not defined.
D. flatMap should be replaced with map.

Solution

  1. Step 1: Analyze the lambda expression

    The lambda tries to multiply it (a list) by 2, which is invalid in Kotlin.
  2. Step 2: Understand flatMap requirements

    flatMap expects a lambda returning an iterable, but it * 2 causes a type error.
  3. Final Answer:

    Cannot multiply a list by an integer directly. -> Option B
  4. Quick Check:

    List * Int is invalid in Kotlin [OK]
Hint: Check types inside lambda; lists can't be multiplied by numbers [OK]
Common Mistakes:
  • Assuming list * number works like in some other languages
  • Thinking flatMap needs a filter
  • Confusing map and flatMap usage
5. Given a list of students where each student has a list of grades, how can you use flatMap to get a single list of all grades above 70?
data class Student(val name: String, val grades: List<Int>)
val students = listOf(
    Student("Alice", listOf(80, 65)),
    Student("Bob", listOf(90, 72)),
    Student("Carol", listOf(60, 85))
)
// Fill in the blank:
val passingGrades = students.flatMap { ________ }
println(passingGrades)
hard
A. it.grades.filter { grade -> grade > 70 }
B. it.grades.map { grade -> grade > 70 }
C. it.grades.filter { grade -> grade < 70 }
D. it.grades

Solution

  1. Step 1: Filter grades above 70 for each student

    Inside the lambda, use it.grades.filter { grade -> grade > 70 } to keep only passing grades.
  2. Step 2: Use flatMap to flatten all filtered grades

    flatMap combines all filtered lists into one flat list of passing grades.
  3. Final Answer:

    it.grades.filter { grade -> grade > 70 } -> Option A
  4. Quick Check:

    flatMap + filter extracts and flattens passing grades [OK]
Hint: Use flatMap with filter inside to flatten filtered results [OK]
Common Mistakes:
  • Using map instead of filter, resulting in booleans
  • Filtering for grades below 70 by mistake
  • Not filtering and returning all grades
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard