Open In App

Kotlin Hashmap

Last Updated : 25 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Kotlin, a HashMap is a collection that stores key-value pairs, where each key must be unique, but values can be duplicated. It is a hash table based implementation of the MutableMap interface. Map keys are unique and the map holds only one value for each key. It is represented as HashMap<key, value> or HashMap<K, V>. The hash table based implementation of HashMap does not guarantees about the order of specified data of key, value and entries of collections.

Constructors of HashMap in Kotlin -

Kotlin provides four public constructors to create a HashMap:

1. HashMap() :

It is the default constructor which constructs an empty HashMap instance.

val hashMap = HashMap<String, Int>()
println("Empty HashMap: $hashMap")

2. HashMap(initialCapacity: Int) :

It is used to construct a HashMap of specified initial capacity. If initialCapacity isn't being used then it will get ignored.

val hashMap = HashMap<String, Int>(10)

3. HashMap(initialCapacity: Int, loadFactor: Float = 0f) :

It is used to construct a HashMap of specified initial capacity and load factor. If initialCapacity and loadFactor isn't being used then both will get ignored.

Note: loadFactor is ignored in Kotlin's current implementation.

4. HashMap(original: Map <out K, V> ) :

It creates instance of HashMap with same mappings as specified map.

val original = mapOf("IronMan" to 3000, "Thor" to 100)
val copyMap = HashMap(original)
println(copyMap)

Important functions of HashMap in Kotlin -

Function

Description

put(key, value)

Inserts or updates the value for the given ke

get(key)

Returns the value for the key or null if not found.

remove(key)

Removes the key-value pair for the given key.

containsKey(key)

Returns true if the map contains the given key.

containsValue(value)

Returns true if the map contains the given value.

clear()

Removes all entries from the map.

size

Returns the number of key-value pairs in the map.

replace(key, value)

Replaces the value for the given key if it exists.


Use of HashMap Functions -

HashMap(), HashMap(original: Map), Traversing hashmap, HashMap.get() - 

Kotlin
fun main() {
    // Initialize HashMap with empty "HashMap of <String, Int>"
    var hashMap : HashMap<String, Int> = HashMap<String, Int> ()

    // print the empty hashMap
    printHashMap(hashMap)

    // use put() to add elements
    hashMap.put("IronMan" , 3000)
    hashMap.put("Thor" , 100)
    hashMap.put("SpiderMan" , 1100)
    hashMap.put("NickFury" , 1200)
    hashMap.put("HawkEye" , 1300)

    // print the non-empty hashMap
    printHashMap(hashMap)
    println("hashMap : " + hashMap + "\n")

    // travarse hashMap using for loop
    for(key in hashMap.keys){
        println("Element at key $key : ${hashMap[key]}")
    }

    // creating another hashMap object with the previous version of hashMap object
    var secondHashMap : HashMap<String, Int> = HashMap<String, Int> (hashMap)

    println("\n" + "Second HashMap : ")
    for(key in secondHashMap.keys){
        //using hashMap.get() function to fetch the values
        println("Element at key $key : ${hashMap.get(key)}")
    }

    //this will clear the whole map and make it empty
    println("hashMap.clear()")
    hashMap.clear()

    println("After Clearing : " + hashMap)


}

// function to print the hashMap
fun printHashMap(hashMap : HashMap<String, Int>){
    // isEmpty() function to check whether the hashMap is empty or not
    if(hashMap.isEmpty()){
        println("hashMap is empty")
    }else{
        println("hashMap : " + hashMap)
    }
}


Output :

hashMap is empty : {}

hashMap : {Thor=100, HawkEye=1300, NickFury=1200, IronMan=3000, SpiderMan=1100}
hashMap : {Thor=100, HawkEye=1300, NickFury=1200, IronMan=3000, SpiderMan=1100}

Element at key Thor : 100
Element at key HawkEye : 1300
Element at key NickFury : 1200
Element at key IronMan : 3000
Element at key SpiderMan : 1100

secondHashMap :
Element at key Thor : 100
Element at key HawkEye : 1300
Element at key IronMan : 3000
Element at key NickFury : 1200
Element at key SpiderMan : 1100

hashMap.clear()
After Clearing : {}


HashMap initial capacity, HashMap.size - 

Kotlin
fun main() {
    // HashMap can also be initialize with its initial capacity.
    // The capacity can be changed by adding and replacing its element.
    var hashMap : HashMap<String, Int> = HashMap<String, Int> (4)

    // use put() to add elements
    hashMap.put("IronMan" , 3000)
    hashMap.put("Thor" , 100)
    hashMap.put("SpiderMan" , 1100)
    hashMap.put("NickFury" , 1200)

    for(key in hashMap.keys) {
        println("Element at key $key : ${hashMap[key]}")
    }
    
    // returns the size
    println("\n" + "hashMap.size : " + hashMap.size )

    // add new element
    hashMap["BlackWidow"] = 1000;
    println("hashMap.size : " + hashMap.size + "\n")

    for(key in hashMap.keys) {
        println("Element at key $key : ${hashMap[key]}")
    }
}

Output:

Element at key Thor : 100
Element at key IronMan : 3000
Element at key NickFury : 1200
Element at key SpiderMan : 1100

hashMap.size : 4
hashMap.size : 5

Element at key Thor : 100
Element at key BlackWidow : 1000
Element at key IronMan : 3000
Element at key NickFury : 1200
Element at key SpiderMan : 1100


HashMap.get(key), HashMap.replace(), HashMap.put() - 

Kotlin
fun main() {
    var hashMap : HashMap<String, Int> = HashMap<String, Int> ()

    // using put() function to add elements
    hashMap.put("IronMan" , 3000)
    hashMap.put("Thor" , 100)
    hashMap.put("SpiderMan" , 1100)
    hashMap.put("Cap" , 1200)

    for(key in hashMap.keys) {
        println("Element at key $key : ${hashMap[key]}")
    }

    // access elements
    println("\nhashMap[\"IronMan\"] : " + hashMap["IronMan"])
    hashMap["Thor"] = 2000
    println("hashMap.get(\"Thor\") : " + hashMap.get("Thor") + "\n")

    // replacing values
    hashMap.replace("Cap" , 999);
    hashMap.put("Thor" , 2000);

    println("hashMap.replace(\"Cap\" , 999)" + " hashMap.replace(\"Thor\" , 2000)) :")

    for(key in hashMap.keys) {
        println("Element at key $key : ${hashMap[key]}")
    }
}

Output:

Element at key Thor : 100
Element at key Cap : 1200
Element at key IronMan : 3000
Element at key SpiderMan : 1100

hashMap["IronMan"] : 3000
hashMap.get("Thor") : 2000

hashMap.replace("Cap", 999) hashMap.replace("Thor", 2000)) :
Element at key Thor : 2000
Element at key Cap : 999
Element at key IronMan : 3000
Element at key SpiderMan : 1100

Time complexity of HashMap -

Kotlin HashMap provides constant time or O(1) complexity for basic operations like get and put, if hash function is properly written and it disperses the elements properly. In case of searching in the HashMap containsKey() is just a get() that throws away the retrieved value, it's O(1) (assuming the hash function works properly).


Some other functions of Kotlin HashMap class -

  • Boolean containsKey(key: K): It returns true if map contains specifies key.
  • Boolean containsValue(value: V): It returns true if map maps one of more keys to specified value.
  • void clear(): It removes all elements from map.
  • remove(key: K): It removes the specified key and its corresponding value from map

In Kotlin, a HashMap is a collection that stores key-value pairs. Each key in a HashMap must be unique, but values can be duplicated. The HashMap class provides methods for adding, removing, and retrieving elements, as well as checking if a key or value is present in the map.

Example of using HashMap in Kotlin:

Kotlin
fun main() {
    // create a new HashMap
    val myMap = hashMapOf<String, Int>()

    // add elements to the HashMap
    myMap.put("apple", 1)
    myMap.put("banana", 2)
    myMap.put("orange", 3)

    // print the HashMap
    println(myMap)

    // remove an element from the HashMap
    myMap.remove("banana")

    // print the updated HashMap
    println(myMap)

    // check if a key is present in the HashMap
    val containsKey = myMap.containsKey("apple")
    println("Contains key 'apple': $containsKey")

    // check if a value is present in the HashMap
    val containsValue = myMap.containsValue(3)
    println("Contains value 3: $containsValue")
}

Output:

{apple=1, banana=2, orange=3}
{apple=1, orange=3}
Contains key 'apple': true
Contains value 3: true

In this example, we create a new HashMap with String keys and Int values. We then add three key-value pairs to the HashMap using the put() method. Next, we print the entire HashMap using the println() function. We then remove the key-value pair with the key "banana" using the remove() method and print the updated HashMap. Finally, we use the containsKey() and containsValue() methods to check if the HashMap contains the key "apple" and the value 3, respectively.

Advantages of HashMap:

  1. HashMap provides a flexible way to store key-value pairs and is easy to use.
  2. HashMap provides efficient O(1) time complexity for basic operations such as adding, removing, and retrieving elements.
  3. HashMap can be used to store a wide variety of data types, including user-defined objects.

Disadvantages of HashMap:

  1. HashMap uses more memory than some other data structures because it stores both keys and values.
  2. HashMap is not thread-safe by default, so concurrent access to a HashMap can cause data corruption or unexpected behavior. If you need to access a HashMap from multiple threads, you should use a thread-safe implementation or use synchronization to ensure thread safety.
  3. The order of elements in a HashMap is not guaranteed, which can be a disadvantage in some cases where element ordering is important. If you need to maintain a specific order of elements, you should use a different data structure such as a LinkedHashMap.

Next Article
Article Tags :
Practice Tags :

Similar Reads