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




KOTLIN - UPDATE MAP


How to update the entries of a Map?


Let us say, we have a Map that contains,

5, Is a Number
John, Is a Name
Kotlin, Is a Language

As Key and Value pair.


Now, let us say, we want to update the value of the Key, 5 with Is an one digit number.


5, Is an one digit number


Where 5 is the Key and Is an one digit number is the new Value.


We can update the entries of a Map using two ways:

  1. Assigning the Value directly by using the Key.


  2. Using the put() Function.


Let us see in the below example using the first way.


Example :



fun main() {

    var x = mutableMapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")
    x[5] = "Is an one digit number"
    println(x)
}


Output :



  {5=Is an one digit number, John=Is a Name, Kotlin=Is a Language}

So, in the above code we have created a Map using mutableMapOf() and Key and Value pairs.


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

And initialised to the variable x.

java_Collections

Now, we are supposed to update the value of the Key, 5 with Is an one digit number.


So, we have used the below way to update it.


x[5] = "Is an one digit number"
java_Collections


And the entry for the Key 5 is updated in the Map.

java_Collections

And we get the below output,

Output :



  {5=Is an one digit number, John=Is a Name, Kotlin=Is a Language}

Let us see the second way of updating the Key Value using the put() Function.


Example :



fun main() {

    var x = mutableMapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")
    x.put(5, "Is an one digit number")
    println(x)
}


Output :



  {5=Is an one digit number, John=Is a Name, Kotlin=Is a Language}

So, in the above code we have created a Map using mutableMapOf and Key and Value pairs.


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

And initialised to the variable x.

java_Collections

Now, we are supposed to update the value of the Key, 5 with Is an one digit number.


So, we have used the below way to update it.


x.put(5, "Is an one digit number")

And the entry for the Key 5 is updated in the Map.

java_Collections

And we get the below output,

Output :



  {5=Is an one digit number, John=Is a Name, Kotlin=Is a Language}