🚀 Enrollments Open for Jetpack Compose Cohort 2 — 7 Days of Live Learning to Build Modern Android UIs 💚Join Now
KotlinIntermediate4 min
Map vs FlatMap in Kotlin?

Recommended Resources

Answer

These are transformation operators for collections and flows.

map

  • Function: Transforms each element T into R.
  • Result: Returns a list of the transformed items.
  • Example: `[1, 2, 3].map { it * 2 } -> [2, 4, 6]`

flatMap

  • Function: Transforms each element T into an Iterable/List of R, and then flattens all the lists into a single list.

  • Result: Returns a single flattened list.

  • Example: ```kotlin val users = listOf(User("A", listOf("Order1")), User("B", listOf("Order2")))

    // map returns List<List<String>> users.map { it.orders } -> [[Order1], [Order2]]

    // flatMap returns List<String> users.flatMap { it.orders } -> [Order1, Order2] ```

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

Accelerate Your Growth

Don't just learn concepts in isolation. Build production-ready Android apps with expert guidance.

Live Interactive Sessions
Code Reviews & Feedback
Real-world Projects
Career Guidance

Limited seats available for next cohort