Kotlin Map flatMap()
Syntax & Examples
Syntax of flatMap()
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.
✐ Examples
1 Flatten a map of lists of strings
In this example,
- We create a map where keys are integers and values are lists of strings.
- We use the
flatMap
function on the map, applying a lambda that accesses the value of each entry and flattens it into a single list. - The resulting list contains all elements from the lists in the map.
- We print the flattened list.
Kotlin Program
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)
}
Output
[one, uno, two, dos]
2 Flatten a map of lists of integers with transformation
In this example,
- We create a map where keys are strings and values are lists of integers.
- We use the
flatMap
function on the map, applying a lambda that maps each integer in the lists to its double value. - The resulting list contains all elements from the transformed lists in the map.
- We print the flattened and transformed list.
Kotlin Program
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)
}
Output
[2, 4, 6, 8]
3 Flatten a list of objects with lists as properties
In this example,
- We define a data class
Person
with a name and a list of hobbies. - We create a list of
Person
objects, each with a name and a list of hobbies. - We use the
flatMap
function on the list ofPerson
objects, applying a lambda that accesses the hobbies list of each person and flattens them into a single list. - The resulting list contains all hobbies from all people in the list.
- We print the flattened list of hobbies.
Kotlin Program
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)
}
Output
[Reading, Running, Swimming, Singing]
Summary
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.