What if you could turn a messy list of lists into one simple list with just one line of code?
Why FlatMap for nested collections in Kotlin? - Purpose & Use Cases
Imagine you have a list of classrooms, and each classroom has a list of students. You want to get a single list of all students from all classrooms.
Manually going through each classroom and then each student is slow and messy. You might write nested loops, which can be confusing and easy to make mistakes in, especially if the data grows.
Using flatMap, you can easily combine all nested lists into one flat list with a simple, clean command. It saves time and reduces errors.
val allStudents = mutableListOf<Student>() for (classroom in classrooms) { for (student in classroom.students) { allStudents.add(student) } }
val allStudents = classrooms.flatMap { it.students }It lets you quickly transform and flatten nested collections into one list, making data easier to work with and understand.
Think of a music app where each playlist has many songs. Using flatMap, you can get one list of all songs from all playlists to create a big mix.
Manually handling nested lists is complicated and error-prone.
flatMap simplifies flattening nested collections into one list.
This makes your code cleaner, faster, and easier to read.
Practice
flatMap function do when applied to a nested list in Kotlin?Solution
Step 1: Understand flatMap behavior
flatMapapplies a transformation to each element and then flattens the nested results into one list.Step 2: Compare with other functions
Unlike sorting, filtering, or converting to a set,flatMapcombines mapping and flattening in one step.Final Answer:
It transforms each element and flattens the result into a single list. -> Option CQuick Check:
flatMap = transform + flatten [OK]
- Confusing flatMap with filter or sort
- Thinking flatMap removes duplicates
- Assuming flatMap only maps without flattening
flatMap on a list of lists named nestedList in Kotlin?Solution
Step 1: Identify correct lambda syntax
TheflatMapfunction requires a lambda to transform each element.{ it }returns each inner list as is.Step 2: Check other options
nestedList.flatMap() misses lambda, C uses wrong arrow syntax, D uses flatten() incorrectly on flat inner lists.Final Answer:
nestedList.flatMap { it } -> Option AQuick Check:
flatMap needs a lambda like { it } [OK]
- Omitting the lambda block
- Using arrow (->) instead of curly braces
- Using flatten() instead of identity mapping
val nested = listOf(listOf(1, 2), listOf(3, 4))
val result = nested.flatMap { it.map { it * 2 } }
println(result)Solution
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).Step 2: Apply flatMap flattening
flatMapflattens the transformed lists into one list: [2, 4, 6, 8].Final Answer:
[2, 4, 6, 8] -> Option DQuick Check:
flatMap + map doubles and flattens [OK]
- Expecting nested lists instead of flat list
- Ignoring the inner map multiplication
- Confusing output with original nested list
flatMap:
val nested = listOf(listOf(1, 2), listOf(3, 4))
val result = nested.flatMap { it * 2 }
println(result)Solution
Step 1: Analyze the lambda expression
The lambda tries to multiplyit(a list) by 2, which is invalid in Kotlin.Step 2: Understand flatMap requirements
flatMapexpects a lambda returning an iterable, butit * 2causes a type error.Final Answer:
Cannot multiply a list by an integer directly. -> Option BQuick Check:
List * Int is invalid in Kotlin [OK]
- Assuming list * number works like in some other languages
- Thinking flatMap needs a filter
- Confusing map and flatMap usage
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)Solution
Step 1: Filter grades above 70 for each student
Inside the lambda, useit.grades.filter { grade -> grade > 70 }to keep only passing grades.Step 2: Use flatMap to flatten all filtered grades
flatMapcombines all filtered lists into one flat list of passing grades.Final Answer:
it.grades.filter { grade -> grade > 70 } -> Option AQuick Check:
flatMap + filter extracts and flattens passing grades [OK]
- Using map instead of filter, resulting in booleans
- Filtering for grades below 70 by mistake
- Not filtering and returning all grades
Ready to prove it?
Pass the test and this pattern moves unknown
