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.
fun main() { val x:HashMap= hashMapOf(5 to "Is a Number", "John" to "Is a Name", "Kotlin" to "Is a Language") println(x) }
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.
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.
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) }
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>()
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")