androidengineers.Book a session
โ† All interview questions
KotlinIntermediate4 min

Map vs FlatMap in Kotlin?

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:
    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]
    

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising