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 ): MThis 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
map1containing integer keys and character values. - We then apply the
toMap()function onmap1. - As a result, a new read-only map containing all key-value pairs from
map1is 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
map2containing character keys and integer values. - We create an empty mutable map named
mutableMap. - We then apply the
toMap()function onmap2, populating themutableMapwith key-value pairs frommap2. - As a result,
mutableMapis returned with the key-value pairs frommap2. - 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
map3containing integer keys and character values. - We create an empty mutable map named
mutableMapwith different key and value types. - We then apply the
toMap()function onmap3, populating themutableMapwith key-value pairs frommap3. - As a result,
mutableMapis returned with the key-value pairs frommap3. - 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.