Advanced Map Operations in Scala

Greetings, Scala enthusiasts! Today, we dive into Scala's elegant data handling capabilities with a focus on the versatile Map. Whether you're organizing a cookbook, tallying votes, or managing an inventory, Map is your go-to tool for efficiently handling key-value pairs. Let's explore how Map can simplify complex tasks through practical examples.

Problem 1: Word Counter

Imagine you have a large text — perhaps a short story or a term paper — and you need to analyze word usage. How frequently does each word appear? A tool like this is invaluable for writers aiming to vary their vocabulary.

Picture yourself developing a feature for a text editor that analyzes word usage. Such a feature could provide writers with valuable feedback, helping them achieve a more dynamic vocabulary.

Naive Approach
Efficient Approach

This is where Map[String, Int] excels, thanks to its efficient key manipulation functions. Instead of laboriously searching for each word, Map allows us to check and update counts quickly, achieving constant time complexity for these operations.

Step by step, here's the streamlined Scala approach:

  1. We create a Map[String, Int] to store words and their frequencies.
  2. Splitting the text into words with the split method.
  3. For each word, update the Map. If the word exists, increment its count; otherwise, add a new entry.

Here's the Scala implementation:

Scala
object Solution {
  def main(args: Array[String]): Unit = {
      val text = "Scala Scala Scala"
      val wordCount = scala.collection.mutable.Map[String, Int]()
      val words = text.split(" ")

      for (word <- words) {
          if (wordCount.contains(word)) {
              wordCount(word) += 1
          } else {
              wordCount(word) = 1
          }
      }
      println(wordCount.mkString(", "))
  }
}

Using the text "Scala Scala Scala" as input would result in a Map with a single entry like: {"Scala" -> 3}. Simple 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