🚀 Enrollments Open for 1:1 Mentorship Scheduled as per your availability 💚Book 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.

1:1 Mentorship

Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.

Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance

Limited slots available each month

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow 💚