Skip to main content

How to retrieve a value from a HashMap using a specific key in Kotlin

How to retrieve a value from a HashMap using a specific key in Kotlin.

Here's a step-by-step tutorial on how to retrieve a value from a HashMap using a specific key in Kotlin:

  1. Create a HashMap:

    val myHashMap = HashMap<String, Int>()

    In this example, we are creating a HashMap that associates keys of type String with values of type Int. You can replace these types with any other types that suit your needs.

  2. Add key-value pairs to the HashMap:

    myHashMap["key1"] = 10
    myHashMap["key2"] = 20
    myHashMap["key3"] = 30

    Here, we are inserting three key-value pairs into the HashMap. You can add as many pairs as you need.

  3. Retrieve a value using a specific key:

    val value1 = myHashMap["key1"]

    You can retrieve a value from the HashMap by using the square bracket notation and providing the key. In this example, we are retrieving the value associated with the key "key1" and storing it in the variable value1.

    Note: If the key is not present in the HashMap, the retrieval operation will return null.

  4. Handle the possibility of a null value:

    if (value1 != null) {
    // Use the retrieved value
    } else {
    // Handle the case when the key is not found
    }

    Since the retrieval operation can return null if the key is not present, it's important to handle this possibility. In this example, we check if value1 is not null before using it. If the key is not found, you can provide an appropriate response in the else block.

  5. Retrieve a value using a specific key and provide a default value:

    val value2 = myHashMap.getOrDefault("key2", 0)

    If you want to provide a default value when the key is not found, you can use the getOrDefault function. In this example, we are retrieving the value associated with "key2", but if the key is not present, it will return 0 instead of null.

  6. Retrieve a value using a specific key and handle the absence of the key:

    val value3 = myHashMap.getOrElse("key3") {
    // Provide a default value or perform some other action
    }

    If you want to provide a custom action or default value when the key is not found, you can use the getOrElse function. In this example, we are retrieving the value associated with "key3", but if the key is not present, we provide a lambda expression that returns a default value or performs some other action.

That's it! You now know how to retrieve a value from a HashMap using a specific key in Kotlin. Remember to handle the possibility of a null value or absent key to ensure your code is robust.