Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




KOTLIN - COPY FROM MAP


How to copy one Map to the other?


There are two ways by which we can copy one Map to the other.

  1. Using the method 'toMap()'


  2. Using the method 'toMutableMap()'


Let us look at the first way using the toMap() method.


Example :



fun main() {

    var x = mapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")
    var y = x.toMap()
    println("The Copied Map is "+y)
}


Output :



  The Copied Map is {5=Is a Number, John=Is a Name, Kotlin=Is a Language}

So, in the above code we have created a Map and initialised to the variable x.


var x = mapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")

Then we have taked the Map x and called the toMap() method that creates a new Map that would be the exact copy of x.


Then assign it to y.


	var y = x.toMap()

And if we see the below output,


The Copied Map is {5=Is a Number, John=Is a Name, Kotlin=Is a Language}

The new variable y is an exact copy of x.


Similarly, we can use toMutableMap() that would create a Mutable Map(i.e. A Map that can be changed/modified).


Example :



fun main() {

    var x = mutableMapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")
    var y = x.toMutableMap()
    println("The Copied Map is "+y)
}


Output :



  The Copied Map is {5=Is a Number, John=Is a Name, Kotlin=Is a Language}

Note : Do not use the '=' operator to copy a Map to the other(i.e. If there are two Dictionaries 'x' and 'y'. Do not use y = x). Because in that case any changes made to the Map 'x' will be reflected in the copied Map 'y'.