Kotlin Tutorials

Kotlin Map toMap()
Syntax & Examples

Syntax of toMap()

There are 2 variations for the syntax of Map.toMap() extension function. They are:

1.
fun <K, V> Map<out K, V>.toMap(): Map<K, V>

This extension function returns a new read-only map containing all key-value pairs from the original map.

2.
fun <K, V, M : MutableMap<in K, in V>> Map<out K, V>.toMap( destination: M ): M

This extension function populates and returns the destination mutable map with key-value pairs from the given map.



✐ Examples

1 Convert to read-only map

In this example,

  • We create a map named map1 containing integer keys and character values.
  • We then apply the toMap() function on map1.
  • As a result, a new read-only map containing all key-value pairs from map1 is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
    val result = map1.toMap()
    println(result)
}

Output

{1=a, 2=b, 3=c}

2 Populate mutable map

In this example,

  • We create a map named map2 containing character keys and integer values.
  • We create an empty mutable map named mutableMap.
  • We then apply the toMap() function on map2, populating the mutableMap with key-value pairs from map2.
  • As a result, mutableMap is returned with the key-value pairs from map2.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
    val mutableMap = mutableMapOf<Char, Int>()
    val result = map2.toMap(mutableMap)
    println(result)
}

Output

{a=1, b=2, c=3}

3 Populate mutable map with different types

In this example,

  • We create a map named map3 containing integer keys and character values.
  • We create an empty mutable map named mutableMap with different key and value types.
  • We then apply the toMap() function on map3, populating the mutableMap with key-value pairs from map3.
  • As a result, mutableMap is returned with the key-value pairs from map3.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
    val mutableMap = mutableMapOf<Int, Char>()
    val result = map3.toMap(mutableMap)
    println(result)
}

Output

{1=a, 2=b, 3=c}

Summary

In this Kotlin tutorial, we learned about toMap() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.