Kotlin Map toMutableMap()
Syntax & Examples
Syntax of toMutableMap()
The syntax of Map.toMutableMap() extension function is:
fun <K, V> Map<out K, V>.toMutableMap(): MutableMap<K, V>
This toMutableMap() extension function of Map returns a new mutable map containing all key-value pairs from the original map.
✐ Examples
1 Convert to mutable map
In this example,
- We create a map named
map1
containing integer keys and character values. - We then apply the
toMutableMap()
function onmap1
. - As a result, a new mutable 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.toMutableMap()
println(result)
}
Output
{1=a, 2=b, 3=c}
2 Convert to mutable map
In this example,
- We create a map named
map2
containing character keys and integer values. - We then apply the
toMutableMap()
function onmap2
. - As a result, a new mutable map containing all key-value pairs from
map2
is returned. - 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 result = map2.toMutableMap()
println(result)
}
Output
{a=1, b=2, c=3}
3 Convert to mutable map
In this example,
- We create a map named
map3
containing string keys and integer values. - We then apply the
toMutableMap()
function onmap3
. - As a result, a new mutable map containing all key-value pairs from
map3
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val result = map3.toMutableMap()
println(result)
}
Output
{apple=1, banana=2, cherry=3}
Summary
In this Kotlin tutorial, we learned about toMutableMap() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.