The syntax of Map.flatMap() extension function is:
fun <K, V, R> Map<out K, V>.flatMap( transform: (Entry<K, V>) -> Iterable<R> ): List<R>
This flatMap() extension function of Map returns a single list of all elements yielded from results of transform function being invoked on each entry of original map.
In this example,
flatMap
function on the map, applying a lambda that accesses the value of each entry and flattens it into a single list.fun main(args: Array<String>) {
val map = mapOf(1 to listOf("one", "uno"), 2 to listOf("two", "dos"))
val flatMapped = map.flatMap { it.value }
println(flatMapped)
}
[one, uno, two, dos]
In this example,
flatMap
function on the map, applying a lambda that maps each integer in the lists to its double value.fun main(args: Array<String>) {
val map = mapOf("A" to listOf(1, 2), "B" to listOf(3, 4))
val flatMapped = map.flatMap { it.value.map { it * 2 } }
println(flatMapped)
}
[2, 4, 6, 8]
In this example,
Person
with a name and a list of hobbies.Person
objects, each with a name and a list of hobbies.flatMap
function on the list of Person
objects, applying a lambda that accesses the hobbies list of each person and flattens them into a single list.fun main(args: Array<String>) {
data class Person(val name: String, val hobbies: List<String>)
val people = listOf(Person("Alice", listOf("Reading", "Running")), Person("Bob", listOf("Swimming", "Singing")))
val flatMapped = people.flatMap { it.hobbies }
println(flatMapped)
}
[Reading, Running, Swimming, Singing]
In this Kotlin tutorial, we learned about flatMap() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.