Counting with HashMaps in Scala

Understanding the Problem

We begin in a library, where we want to count book copies. With a small collection, we might be able to tally each one manually. However, as the collection grows, this approach becomes cumbersome and inefficient. A more efficient method uses a HashMap, or a Map in Scala.

For a quick illustration, consider this list of colors:

val colors = List("red", "blue", "red", "green", "blue", "blue")

If we count manually, red appears twice, blue appears thrice, and green appears once. We can employ HashMaps for a more efficient counting process.

Introducing HashMaps

Simple yet powerful, HashMaps allow us to store and retrieve data using keys. The unique colors in our list act as keys, and the count of each color becomes its corresponding value. Let's demonstrate how we can count elements in our colors list using a Scala Map:

val colors = List("red", "blue", "red", "green", "blue", "blue")
var colorMap = Map[String, Int]()

// Start the loop to iterate over each color
for (color <- colors) {
  // If the color is present in our map, increment its value by 1; otherwise set its value to 1
  colorMap = colorMap.updated(color, colorMap.getOrElse(color, 0) + 1)
}

// Print our map with counts
println(colorMap)
// prints Map(red -> 2, blue -> 3, green -> 1)

When the above code executes, it displays the counts for each color: Map(red -> 2, blue -> 3, green -> 1).

Understanding the Above Solution

Here's how we created a map to count our elements:

We began with an empty map. Then, we went through our list, and for each occurring element, we used the getOrElse method to check if it was in our map. If it was, we increased its value. If it was not, we added it to the map with a value of 1.

The updated method was used to modify our map. The syntax for the updated method is as follows:

map.updated(key, value)

This method returns a new map with the specified key updated to the given value. If the key already exists in the map, its value is replaced; if it doesn't exist, the key-value pair is added to the map. In our example, colorMap = colorMap.updated(color, colorMap.getOrElse(color, 0) + 1) updates the map by either incrementing the count of the existing color or adding the color with an initial count of 1.

Consequently, this code efficiently counts the colors in our list, showcasing how performant counting can be, even as the list size increases!

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