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




KOTLIN - HASHMAP


As the name suggests, HashMap is an implementation of Map, which follows a technique called Hashing.


Since, the insertion is based on something called as Hash Code, a HashMap is unsorted and unordered.


Note : It is not mandatory to understand 'Hashing' and 'Hash Code' to understand 'HashMap'. However, it's good to know them.

Creating a 'HashMap' with keys and values of 'Any' Data Type


Example :



fun main() {
    val x:HashMap = hashMapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")
    println(x)
} 


Output :



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

So, we have created a HashMap and assigned three values as Key, value pairs to it.


val x:HashMap = hashMapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language")

It is almost same as creating a Map. Just that after the variable name, you need to specify HashMap with Any inside angular brackets.


Note : We are using 'Any' because this HashMap can accept different data types.
java_Collections

Now, if you see the output, it is not printed in the same order it was inserted.


That is because insertion order in HashMap is not maintained.


Creating an empty 'HashMap' with Keys of Int and values of String Data Type


Example :



fun main() {
    val x:HashMap<Int, String> = HashMap<Int,String>()

    x.put(1, "Number One")
    x.put(2, "Number Two")
    x.put(3, "Number Three")
    println(x)
} 


Output :



  {1=Number One, 2=Number Two, 3=Number Three}

So, in the above example, we have created a HashMap that would only accept an Int data as Key and String data as Value.


val x:HashMap<Int, String> = HashMap<Int,String>()
java_Collections


Then we have used put() method to insert values to the HashMap.


x.put(1, "Number One")
x.put(2, "Number Two")
x.put(3, "Number Three")
java_Collections