Kotlin Tutorials

Kotlin Map flatMapTo()
Syntax & Examples

Syntax of flatMapTo()

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.



✐ Examples

1 Duplicate each character and its uppercase

In this example,

  • We create a map named map1 containing pairs of numbers and characters.
  • We initialize an empty mutable list named result1.
  • We apply the flatMapTo() function on map1, transforming each entry into a list containing the character value and its uppercase equivalent.
  • The resulting list is printed to standard output.

Kotlin Program

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)
}

Output

[a, A, b, B, c, C]

2 Duplicate each number and its double

In this example,

  • We create a map named map2 containing pairs of characters and numbers.
  • We initialize an empty mutable list named result2.
  • We apply the flatMapTo() function on map2, transforming each entry into a list containing the number value and its double.
  • The resulting list is printed to standard output.

Kotlin Program

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)
}

Output

[1, 2, 2, 4, 3, 6]

3 Duplicate each number and its double as many times as its value

In this example,

  • We create a map named map3 containing pairs of strings and numbers.
  • We initialize an empty mutable list named result3.
  • We apply the flatMapTo() function on map3, transforming each entry into a list containing each number and its double repeated based on its value.
  • The resulting list is printed to standard output.

Kotlin Program

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)
}

Output

[0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 10, 0, 2, 4, 6, 8, 10, 12]

Summary

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.