Exploring HashMaps in Kotlin

Introduction to HashMaps

Hi, and welcome! Today, we'll explore HashMaps, a data structure that organizes data as key-value pairs, much like a treasure box with unique labels for each compartment.

Imagine dozens of toys in a box. If each toy had a unique label (the key), you could directly select a toy (the value) using the label. No rummaging required — that's the power of HashMaps! Today, we'll understand HashMaps and learn how to implement them in Kotlin.

Understanding HashMaps

HashMaps are special types of data structures that utilize unique keys instead of indexes. When you know the key (toy's label), you can directly pick up the value (toy). That's how a HashMap works!

Consider an oversized library of books. With HashMaps (which act like the library catalog), you'll quickly locate any book using a unique number (key)!

HashMaps in Kotlin

Kotlin implements HashMaps through its standard library using both the mutableMapOf() and the hashMapOf() functions to hold data in key-value pairs. While both can create mutable maps, they have subtle differences:

  • mutableMapOf() creates a mutable map with default settings, but it doesn't guarantee the use of a specific map implementation. In practice, it often uses a LinkedHashMap, which maintains the order of insertion.

  • hashMapOf() specifically creates an instance of java.util.HashMap, which does not maintain any order of keys or insertion.

The choice between them depends on whether the order of insertion matters in your application. If order is crucial, opt for mutableMapOf(). Otherwise, you can use either as needed. Here's an example of creating a HashMap, functioning as a catalog for a library:

fun main() {
    // Using hashMapOf
    val libraryCatalog = hashMapOf(
        "book1" to "A Tale of Two Cities",
        "book2" to "To Kill a Mockingbird",
        "book3" to "1984"
    )
}

In this HashMap, book1, book2, and book3 are keys, while the book titles serve as their respective values.

It's important to remember that the keys should be of a type that supports hashing and equality comparison. Examples include String, Short, Int, Long, Float, Double, Char, and Boolean. The values can be of any type.

HashMap Operations: Accessing, Updating, and Removing Elements

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal