HashMap in Kotlin : Key Value Pair Data Structure

Home » Kotlin » HashMap in Kotlin : Key Value Pair Data Structure

HashMap is a collection class in Kotlin that provides a key-value pair data structure. It implements the Map interface and allows storing and retrieving elements based on unique keys. Let’s explore HashMap in Kotlin programming language.

HashMaps use hashing algorithms internally to efficiently locate and access elements, making them an ideal choice for scenarios requiring fast key-based lookup.

HashMap in Kotlin : Key Value Pair Data Structure

Creating a HashMap in Kotlin

To create a HashMap in Kotlin, you can use the hashMapOf() function or the HashMap() constructor.

Kotlin : hashMapOf() Function

fun main()
{
    val androidOS = hashMapOf<String, Double>(
        "Cupcake" to 1.5,
        "Eclair" to 2.1,
        "Jelly Bean" to 4.2,
        "KitKat" to 4.4
    )
    println(androidOS)
}

The program creates a HashMap named androidOS in Kotlin, which stores information about different versions of the Android operating system along with their corresponding version numbers.

The HashMap is declared with the val keyword, indicating that it is immutable (read-only) once initialized. The keys in this HashMap are of type String, representing the names of the Android OS versions, while the values are of type Double, representing the version numbers.

The hashMapOf() function is used to create the HashMap instance. Inside the parentheses, the key-value pairs are defined using the to keyword, where the key is followed by to and then the corresponding value. The example includes four key-value pairs representing different Android OS versions and their version numbers.

Example : “Cupcake” to 1.5: This pair associates the name “Cupcake” with the version number 1.5″

Output

{Eclair=2.1, KitKat=4.4, Jelly Bean=4.2, Cupcake=1.5}

Once the HashMap is created, it can be used to retrieve version numbers by providing the corresponding Android OS name as the key. For example, androidOS[“KitKat”] would return the value 4.4.

Common Operations on HashMaps

HashMaps offer a variety of operations to manipulate and retrieve data efficiently. Let’s explore some of the commonly used operations.

  // access the version number
    val version = androidOS["KitKat"]
    println(version)

Iterating over HashMap (using for loop)

    // iterating over hashMap
    for ((key, value) in androidOS)
    {
        println("$key : $value")
    }
Eclair : 2.1
KitKat : 4.4
Jelly Bean : 4.2
Cupcake : 1.5

Iterating over HashMap (using forEach)

  // using forEach
    androidOS.forEach{
        (key, value) ->
        println("$key : $value")
    }

Adding and Updating Elements

 androidOS["Oreo"] = 8.0
    // or
    androidOS.put(key = "Pie", value = 9.0)
    println(androidOS)

Output

{Eclair=2.1, KitKat=4.4, Oreo=8.0, Jelly Bean=4.2, Pie=9.0, Cupcake=1.5}

Let’s use HashMap() constructor to make HashMap

 // using HashMap constructor
    val colors = HashMap<Int, String>().apply {
        put(1, "Blue")
        put(2, "Green")
        put(3, "Red")
    }
    println(colors)

Output

{1=Blue, 2=Green, 3=Red}

Remove an element from HashMap

Write the below program in Kotlin Playground

fun main()
{
   // using HashMap constructor
    val colors = HashMap<Int, String>().apply {
        put(1, "Blue")
        put(2, "Green")
        put(3, "Red")
    }
 colors.remove(1) //Removes Blue
 colors.forEach{(value, color) -> println("Value: $value, Color: $color" ) }

}

Output

Value: 2, Color: Green
Value: 3, Color: Red

To clear the HashMap :

colors.clear()

Empty check on HasMap:

val check =  colors.isEmpty()
val find =  if (check) "Yes" else "NO"
println(find)

[Learn more about Kotlin’s Conditional Expression]

Output

NO

Play with HashMap properties

 val size = colors.size
 val isEmpty = colors.isEmpty()
 val containsKey = colors.containsKey(2)
 val containsValue = colors.containsValue("Red")

HashMaps can be used as a cache to store computed values for faster access in subsequent computations. This approach is useful when the same computation is required multiple times.

You may also like...