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




KOTLIN - MAP


A Map is a Collection that can also hold multiple values in Key and Value pairs. In the Map, the elements are unordered, unindexed, changeable and doesn't allow duplicate values.


You can think of a Map like an actual English Dictionaries. Where you search for a word and you get its explanation.


The declaration of a Map is also quite simple. You can place multiple values inside the mapOf() method in the form of Key and Value pairs.


Just imagine the Key to be the word you are going to search in the English Dictionary. And the Value is the explanation you find in it.


Creating a 'Map' with values of different Data Types


Example :



fun main() {
    var x = mapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")
    println(x)
} 


Output :



  {5=Is a Number, John=Is a Name, Kotlin=Is a Language}

So, in the above code we have created a Map using mapOf() method. And the values are represented in Key and Value pairs.


The Key is a number or a String and in the value we have provided its explanation(Somewhat like the English Dictionary).


i.e. We know that the first element 5 is a number. So, in the Key, we have put the number 5 and in its value, we have put the explanation, Is a Number. Same logic is applicable for the other two Keys, John and Kotlin.


A Key and Value is separated by keyword to.


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


And initialised to the variable x.

java_Collections

And in the next line we have printed the Map using the print statement.


println(x)

Now, if we see the output,

Output :



  {5=Is a Number, John=Is a Name, Kotlin=Is a Language}

The output contains Key and Value separated by =.

java_Collections

But just remember, while we declare a Map, the Key and Value is separated by keyword to.

java_Collections