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
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