What is "flatMap()" method in Kotlin?

Kotlin is a modern programming language with clear syntax and powerful features. It is prominent across various industries, from Android app development to backend applications.

The flatMap() method

The flatMap() method helps flatten nested collections and allows the extraction and transformation of elements efficiently. It combines map and flatten operations and flatMap() simplifies complex data manipulations. It reduces the need for nested loops and complex logic, resulting in cleaner code.

Syntax

The syntax for the flatMap() method in Kotlin is given below:

fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R>
Syntax for flatMap() method
  • T is the type of elements in the original collection.

  • R represents the type of elements in the resulting collection.

  • transform is a lambda function that maps each element of the original collection to an iterable of the desired type.

Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.

Code

Let’s consider a code example to demonstrate the use of flatMap() method.

Suppose we have a list of strings and want to split each string into words using this method.

fun main() {
val phrases = listOf("Welcome to", "Educative Answers", "Kotlin is used for mobile development.")
val words = phrases.flatMap { it.split(" ") }
println(words)
}

Code explanation

  • Line 1–2: Firstly, we define with a list of three phrases.

  • Line 4: Next, we use flatMap() method while applying the split(" ") function to each phrase, which splits the phrases into words.

  • Line 6: Lastly, we print the result as a flattened list of words on the console.

Output

Upon execution, the code will flatten strings in the defined list and split them into separate words.

The output looks something like this:

[Welcome, to, Educative, Answers, Kotlin, is, used, for, mobile, development.]

Conclusion

Therefore, the flatMap() method in Kotlin serves as an essential tool for transforming collections. It can flatten nested collections, simplify data operations, and improve code readability. Developers can create more concise, efficient, and expressive code by employing this method in their Kotlin applications.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved