The syntax of Map.flatMapTo() extension function is:
fun <K, V, R, C : MutableCollection<in R>> Map<out K, V>.flatMapTo( destination: C, transform: (Entry<K, V>) -> Iterable<R> ): C
This flatMapTo() extension function of Map appends all elements yielded from results of transform function being invoked on each entry of original map, to the given destination.
In this example,
map1
containing pairs of numbers and characters.result1
.flatMapTo()
function on map1
, transforming each entry into a list containing the character value and its uppercase equivalent.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val result1 = mutableListOf<Char>()
map1.flatMapTo(result1) { (_, value) -> listOf(value, value.toUpperCase()) }
println(result1)
}
[a, A, b, B, c, C]
In this example,
map2
containing pairs of characters and numbers.result2
.flatMapTo()
function on map2
, transforming each entry into a list containing the number value and its double.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val result2 = mutableListOf<Int>()
map2.flatMapTo(result2) { (_, value) -> listOf(value, value * 2) }
println(result2)
}
[1, 2, 2, 4, 3, 6]
In this example,
map3
containing pairs of strings and numbers.result3
.flatMapTo()
function on map3
, transforming each entry into a list containing each number and its double repeated based on its value.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
val result3 = mutableListOf<Int>()
map3.flatMapTo(result3) { (_, value) -> List(value) { it * 2 } }
println(result3)
}
[0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 10, 0, 2, 4, 6, 8, 10, 12]
In this Kotlin tutorial, we learned about flatMapTo() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.