Properties & Functions of Kotlin HashMap
Also, note that this interface of Maps is immutable, has a fixed size, and all of its methods are read-only. So, to overcome this immutable nature of maps, we use Hashmap.
The Kotlin HashMap class uses a Hash table to implement the MutableMap interface. It also keeps the information in the form of a key-value pair.
Syntax to use Hashmap is HashMap<key, value>.
HashMapOf() is a HashMap class function. It creates a new HashMap with the specified contents. It holds data in the form of key-value pairs. Since HashMap is a mutable collection, it supports both read and write operations.
Note: The HashMap class's implementation makes no assurances about the order of key, value, or collection items.
Some examples of functions and constructor in them are:
HashMap() Constructor
It creates a HashMap instance that is empty.
HashMap(initialCapacity: Int, loadFactor: Float = 0f) Constructor
It is used to make a HashMap with a specified capacity(given by Int).
HashMap(original: Map<out k, v>) Constructor
It creates a HashMap instance with the contents of the original map supplied in <k,v> pair.
Function put(key: k, value: v)
This function puts the specified key(k) and value(v) in the map.
Function clear()
This function clears out all the elements from the map.
Function remove(key: k)
It deletes the provided key and its value from the map.
Function get(key: k)
It returns the value of the supplied key or null if there is no such key in the map.
Function containsKey(key: k)
If the map contains the specified key, it returns true.
Function containsValue(value: v)
If the map maps one or more keys to the supplied value, it returns true.
Properties & Functions of Mutable Map
Kotlin MutableMap is a collection framework interface that contains objects in the form of key-value pairs. Using their respective keys, the values of the MutableMap interface are obtained and every key of the mutable map can hold only 1 value too.
MutableSet<MutableEntry<k, v>>
This returns a MutableSet containing all the map's key and value pairs.
MutableSet<k>
This retrieves all MutableSet keys in this map.
MutableCollection<v>
This returns all the values of MutableCollection in the current map. This collection may contain duplicate values.
All the functions like:
put(key: K, value: V)
remove(key: K)
clear()
containsKey(key: K)
getValue(key: K)
They also work in Mutable Map in the same manner.
Examples
Now let us take a deep dive into Kotlin Maps and Hashmaps with some programmatically working examples.
Declaring and Traversing a map
We can do so with the help of the mapOf<k,v>(). Let us see this with an example-
Code:
fun main() {
val my_map = mapOf<String,String>("Akshit" to "Roll No.1", "Rahul" to "Roll No.2", "Aman" to "Roll No.3")
for(key in my_map.keys){ println(my_map[key])
}
}
Output:
Roll No.1
Roll No.2
Roll No.3
Note that here we have used both key and value as string types. But, both of them can be a mix of any data type like:
Code:
fun main() {
val my_map: Map<Int, String> = mapOf<Int,String>(1 to "Roll No.Akshit", 10 to "Roll No.Rahul", 100 to "Roll No.Aman")
for(key in my_map.keys){
println("When key is $key then value is ${my_map.get(key)}")
}
}
Output:
When key is 1 then value is Roll No.Akshit
When key is 10 then value is Roll No.Rahul
When key is 100 then value is Roll No.Aman
Here the key is Int type and value is String type.
Using maps(with no datatype for key-value)
Keep that in mind that If we are unable to provide any type of key and value for the Map Interface, it will accept any type of key and value. This is due to the fact that all classes use <Any type, Any type> data types internally. Consider the following scenario:
Code:
fun main() {val my_map = mapOf(1 to "Roll No.Akshit", 10 to "Roll No.Rahul", 100 to 1000,"Radha" to "Krishan", "fifty" to 50)
for(key in my_map.keys){
println("When key is $key then value is ${my_map.get(key)}")
}
}
Output:
When key is 1 then value is Roll No.Akshit
When key is 10 then value is Roll No.Rahul
When key is 100 then value is 1000
When key is Radha then value is Krishan
When key is fifty then value is 50
Various functions of mapOf()
The use of mapOf() function in maps is shown below with an example-
Code:
fun main() {
val my_map: Map<Int,String> = mapOf<Int, String>(1 to "Akshit", 10 to "Rahul", 100 to "Aman")
for(key in my_map.keys){
println("When key is $key then value is ${my_map.get(key)}")
}
println()
println("When getValue(10) is used, it returns value at key = 10") // mapOf().getValue() function
println(my_map.getValue(10))
println()
println("When contains(100) is used, itchecks if entered key = 100 is present or not and returns boolean") // mapOf().contains() function
println( my_map.contains(100))
println()
println("When containsKey(1000) is used, it have similar function like contains() to check key presence ") // mapOf().containsKey() function
println(my_map.containsKey(1000))
println()
println("When containsValue() is used, it checks if 'Akshit' value is present or not ") // mapOf().containsValue() function
println(my_map.containsValue("Akshit"))
println()
println("When map.get(1) is used, it returns value at key 1") // mapOf().get() function
println(my_map.get(1))
println()
println("When map.getOrDefault(100, "rahul") is used, it returns value at key '100' and incase not present , it ives default one ")
// mapOf().getOrDefault() function
println(my_map.getOrDefault(100, "Rahul"))
println()
println("checking all values and their keys") //mapOf().iterator() function
for(var_x in my_map.iterator()){
println("key = ${var_x.key} value = ${var_x.value}")
}
println()
println("When map.minus(100) is used, it will remove value at key = 100") // mapOf().minus() function
for(x in my_map.minus(100)){
println(my_map[x.key])
}
println()
println("When map.plus() is used, it will add 'munna bhai' value at key = 100 ") // mapOf().plus()
for(varX in my_map.plus(Pair(100, "munna bhai"))){
println("When key is ${varX.key} then value is ${varX.value}")
}
}
Output:
When key is 1 then value is Akshit
When key is 10 then value is Rahul
When key is 100 then value is Aman
When getValue(10) is used, it returns value at key = 10
Rahul
When contains(100) is used, itchecks if entered key = 100 is present or not and returns boolean
true
When containsKey(1000) is used, it have similar function like contains() to check key presence
false
When containsValue() is used, it checks if 'Akshit' value is present or not
true
When map.get(1) is used, it returns value at key 1
Akshit
When map.getOrDefault(100, "rahul") is used, it returns value at key '100' and incase not present , it ives default one
Aman
checking all values and their keys
key = 1 value = Akshit
key = 10 value = Rahul
key = 100 value = Aman
When map.minus(100) is used, it will remove value at key = 100
Akshit
Rahul
When map.plus() is used, it will add 'munna bhai' value at key = 100
When key is 1 then value is Akshit
When key is 10 then value is Rahul
When key is 100 then value is munna bhai
Creating a Hashmap
Let's see how to create a Hashmap with this example:
Code:
fun main() {
val hashMap:HashMap<Int,String> = HashMap<Int,String>() //It defines an empty hashmap
hashMap.put(1,"Akshit") // elements are getting added in hashmap from here
hashMap.put(3,"Rahul")
hashMap.put(4,"Aman")
hashMap.put(2,"munna bhai")
println()
for(var_x in hashMap.keys){ // var_x is reviewing key from for() loop
println("When key is $var_x then value is ${hashMap[var_x]}")
}
}
Output:
When key is 1 then value is Akshit
When key is 2 then value is munna bhai
When key is 3 then value is Rahul
When key is 4 then value is Aman
Functions in Hashmap
Let’s see the experimental usage of remove(), put() and many other functions in Hashmap with this example.
Code:
fun main() {
val hashMap:HashMap<Int,String> = HashMap<Int,String>() //It defines an empty hashmap
hashMap.put(1,"Akshit") // elements are getting added in hashmap from here
hashMap.put(2,"Rahul")
hashMap.put(3,"Aman")
hashMap.put(4,"munna bhai")
println()
for(var_x in hashMap.keys){ // var_x is receiving key from for() loop
println("When key is $var_x then value is ${hashMap[var_x]}")
}
println()
hashMap.replace(4,"munna bhai mbbs")
hashMap.put(2,"simran")
println("Using replace() and put()")
for(var_x in hashMap.keys){
println("When key is $var_x then value is ${hashMap[var_x]}")
}
println()
println("When hashMap.containsKey(3) is used, it will check presence of entered key(3 here) and return boolean")
println(hashMap.containsKey(3))
println(" When hashMap.containsValue(Akshit) is used, it will check presence of entered value(Akshit here) and return boolean")
println(hashMap.containsValue("Akshit"))
println("Current values in hashmap:")
println(hashMap)
println("Values after using clear():")
hashMap.clear()
println(hashMap)
}
Output:
When key is 1 then value is Akshit
When key is 2 then value is Rahul
When key is 3 then value is Aman
When key is 4 then value is munna bhai
Using replace() and put()
When key is 1 then value is Akshit
When key is 2 then value is simran
When key is 3 then value is Aman
When key is 4 then value is munna bhai mbbs
When hashMap.containsKey(3) is used, it will check presence of entered key(3 here) and return boolean
true
When hashMap.containsValue(Akshit) is used, it will check presence of entered value(Akshit here) and return boolean
true
Current values in hashmap:
{1=Akshit, 2=simran, 3=Aman, 4=munna bhai mbbs}
Values after using clear():
{}
Using hashMapOf()
We can declare hashMapOf() function of HashMap in different generic types like:
hashMapOf<Int, String>(), hashMapOf<String, String>().
Let’s see an example covering all your queries about the way of using hashMapOf().
Code:
fun main() {
val stringMap: HashMap<String,String> = hashMapOf<String,String>()
stringMap.put("Coding", "Ninjas")
stringMap.put("Blog", "onKotlin")
stringMap.put("by", "writer")
stringMap.put("Akshit", "Pant")
for(key in stringMap.keys){
println("When Key is: ${key} then value is: ${stringMap[key]}.")
}
println()
println("When containsKey(Coding) is used, it checks if entered key is present or not and returns boolean")
println(stringMap.containsKey("Coding"))
println()
println("When containsValue() is used, it checks if entered value is present or not and returns boolean")
println(stringMap.containsValue("writer"))
println(stringMap.containsValue("Android"))
println()
println("When contains(Blog) is used, it checked if 'Blog' is present in key-value pair in our map or not and returns boolean")
println(stringMap.contains("Blog"))
println()
println()
stringMap.replace("Blog","material")
for(key in stringMap.keys){
println("When Key is: ${key} then value is: ${stringMap[key]}.")
}
println()
println(" When replace(key, oldValue, newValue) is used, it replaces 'Pant' with new entered value(Singh) at specified key(Akshit)")
println(stringMap.replace("Akshit", "Pant","Singh"))
for(key in stringMap.keys){
println("When Key is: ${key} then value is: ${stringMap[key]}.")
}
println()
println("When remove(by) is used, it will remove key 'by' and its corresponding value from the map")
println(stringMap.remove("by"))
for(key in stringMap.keys){
println("When Key is: ${key} then value is: ${stringMap[key]}.")
}
println()
println("When clear() is used, it clears up the occupied space")
println(stringMap) // before clear()
println(stringMap.clear())
println(stringMap) // after clear()
}
Output:
When Key is: Coding then value is: Ninjas.
When Key is: by then value is: writer.
When Key is: Blog then value is: onKotlin.
When Key is: Akshit then value is: Pant.
When containsKey(Coding) is used, it checks if entered key is present or not and returns boolean
true
When containsValue() is used, it checks if entered value is present or not and returns boolean
true
false
When contains(Blog) is used, it checked if 'Blog' is present in key-value pair in our map or not and returns boolean
true
When Key is: Coding then value is: Ninjas.
When Key is: by then value is: writer.
When Key is: Blog then value is: material.
When Key is: Akshit then value is: Pant.
When replace(key, oldValue, newValue) is used, it replaces 'Pant' with new entered value(Singh) at specified key(Akshit)
true
When Key is: Coding then value is: Ninjas.
When Key is: by then value is: writer.
When Key is: Blog then value is: material.
When Key is: Akshit then value is: Singh.
When remove(by) is used, it will remove key 'by' and its corresponding value from the map
writer
When Key is: Coding then value is: Ninjas.
When Key is: Blog then value is: material.
When Key is: Akshit then value is: Singh.
When clear() is used, it clears up the occupied space
{Coding=Ninjas, Blog=material, Akshit=Singh}
kotlin.Unit
{}
Must Read Elvis Operator Kotlin
You can also read about the topic - hash function in data structure
FAQs
-
How can we find the size of our HashMap?
We can easily access the size of our HashMap using hashMapOf().size.
So just run the command: println(stringMap.size) .
-
What is the Time Complexity of HashMap?
The put(), contains(), and remove() actions on a HashMap have an average time complexity of O(1).
-
Is there any difference between Maps and HashMap?
Yes, Map is an interface and it can be implemented using its implementing class. On the other hand, Hashmap is a class of Java collection framework.HashMap implements the Map interface and extends the Abstract Map class.
Key Takeaways
Cheers on reaching here!
The purpose of this article was to introduce the reader to the Kotlin Maps, HashMap and give some basic ideas about how to initialize and use them with their properties and functionalities.
If anyone wants to set up their Kotlin environment for programming, then here is the help.
Recommended Readings:
However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications. Till then, Happy Learning!