Advanced HashMap Operations in Kotlin

Advanced HashMap Operations in Kotlin

Welcome, Kotlin enthusiasts! Today, we'll delve into the powerful world of Kotlin's HashMap! Whether you're managing recipe ingredients, counting votes, or tracking inventory, HashMap is your go-to tool for handling key-value pairs efficiently. Let's explore how it can simplify complex tasks with practical examples.

Problem 1: Word Counter

Imagine you have a long piece of text — maybe a novel or an article — and you want to analyze word frequency. Understanding how often each word appears can help writers diversify their language use.

Picture being tasked with building a text analysis feature for a word processor. This tool could assist writers in refining their language for a more varied vocabulary.

Naive Approach

Consider iterating over the text word by word, using lists to track word occurrences. While feasible for short texts, such a method becomes inefficient for larger documents. As the list grows, updating counts involves iterating through the entire list to find each word, resulting in a time complexity of O(n) per word. Hence, for n words, you'll be dealing with an overall complexity of O(n^2), which is suboptimal for extensive datasets.

Kotlin
fun main() {
    val text = "Kotlin Kotlin Kotlin"
    val wordsList = mutableListOf<String>()
    val countList = mutableListOf<Int>()
    val words = text.split(" ")

    for (word in words) {
        val index = wordsList.indexOf(word)
        if (index != -1) {
            countList[index]++
        } else {
            wordsList.add(word)
            countList.add(1)
        }
    }

    for (i in wordsList.indices) {
        println("${wordsList[i]}: ${countList[i]}")
    }
}

The split function in Kotlin divides a string into substrings based on specified delimiters and returns a list of these substrings.

Efficient Approach

Enter HashMap<String, Int>, our efficiency champion! With its quick key manipulation functions like containsKey and getOrPut, a HashMap allows for swift updates. Instead of searching laboriously for each word, you can promptly check and update its count, saving you substantial time.

Here's the efficient Kotlin solution broken down:

  1. Create a HashMap<String, Int> named wordCount for words and their frequencies.
  2. Use the split function to break the text into words.
  3. For every word, update the HashMap using getOrPut. Increment the count if the word exists; otherwise, initialize it with a count of 1.

The getOrPut function retrieves a value if the key exists, or executes the lambda in curly brackets { } to insert and return a default value if it doesn't — so wordCount.getOrPut(word) { 0 } returns the current count or 0 for new words.

Here's how it's done in Kotlin:

Kotlin
fun main() {
    val text = "Kotlin Kotlin Kotlin"
    val wordCount = hashMapOf<String, Int>()
    val words = text.split(" ")

    for (word in words) {
        wordCount[word] = wordCount.getOrPut(word) { 0 } + 1
    }
    println(wordCount)
}

Consider the sentence "Kotlin Kotlin Kotlin." Our function creates a HashMap with a single entry: {"Kotlin" to 3}. Clean and efficient!

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