Scala Map

Learn via video courses
Topics Covered

Overview

Map in Scala is a data structure that allows you to store key-value pairs, where each key is unique within the map. It provides an efficient way to retrieve values based on their associated keys. Scala offers two main types of maps, mutable map and immutable map. Its versatility and flexibility make it invaluable for a wide range of programming tasks. Whether we choose mutable maps for frequent modifications or opt for immutable maps to embrace functional programming principles, understanding the strengths and appropriate use cases of each will help us write more robust and maintainable code.

How to Create Scala Maps?

Scala provides two main types of maps which are mutable maps and immutable maps.

Mutable Maps

Mutable maps as their name suggests allow modification of their content after creation. They are part of the scala.collection.mutable package.

  • To create a mutable map in Scala, import the mutable.Map class from the scala.collection.mutable package:

  • Now, create an instance of the mutable.Map class and initialize the key value-pairs in the constructor:

Immutable Maps

Immutable maps cannot be modified once they are created. Instead of changing an existing map, any updates result in the creation of a new map.

  • To create an immutable map in Scala, import the immutable.Map class from the scala.collection.immutable package ( note that the import might not be necessary as immutable maps are part of the default namespace):

  • Now, create an instance of the immutable.Map class and Use the -> operator to create key-value pairs.

Syntax

Both mutable and immutable maps share similar syntax, with the only difference being that while creating mutable maps, we need to explicitly import the mutable.Map class from the scala.collection.mutable package.

Syntax for creating a mutable map in Scala:

Syntax for creating an immutable map in Scala:

Immutable maps are part of the default namespace, so we don't need to import any package explicitly.

syntax of creating mutable and immutable maps in scala

Operations on a Scala Map

Map in Scala offers a variety of operations that enable us to manipulate and access data effectively. Below are some of the most common operations on Scala maps:

  • keys: Iterable[K]:
    It returns an iterable containing a collection of all keys in the map.

    Example:

  • values: Iterable[V]:
    It returns an iterable containing a collection of all values in the map.

    Example:

  • isEmpty: Boolean:
    It checks if the map is empty (contains no key-value pairs). It returns true if the map is empty otherwise false.

    Example:

  • size: Int:
    It returns the total number of key-value pairs in the map.

    Example:

  • get(key: K): Option[V]:
    It retrieves the value associated with the given key wrapped in an Option. It returns Some(value) if the key exists, or None if the key is not present in the map.

    Example:

  • contains(key: K): Boolean:
    It checks whether the map contains a specific key. It returns true if the map contains the key otherwise false.

    Example:

Accessing Values Using Keys

Accessing values using keys in a map in Scala can be done using the apply method or the get method. Both methods allow us to retrieve the value associated with a specific key. However, the get method returns an Option type, which helps to handle cases where the key might not exist in the map. Let's explore both approaches:

Using the "apply" Method:

The apply method allows us to directly access the value associated with a given key. If the key does not exist in the map, it will throw a NoSuchElementException.

Example:

Using the "get" Method:

The get method returns an Option type, which wraps the value if the key is found in the map (Some(value)). If the key does not exist, it returns None.

Example:

Updating the Values

Updating values in Scala maps refers to changing the values in key-value pairs after the creation of maps.

Updating Immutable Map

Since immutable maps are, by definition, not modifiable, we create a new map with the updated content. This means that the original map remains unchanged, and we work with the updated map to change any key-value pair.

Example:

In the example above, we first create a new map modifiedMap with the value of the "banana" key updated to 5. Then, we create a new map updatedMap with an additional key-value pair "grape" -> 4. Lastly, we create a new map removedMap without the "orange" key.

Updating Mutable Map

Since mutable maps are changeable, to update values in a mutable map, we can directly assign the new value to the existing key.

Example:

In the example above, we first update the value of the "banana" key from 2 to 5. Then, we add a new key-value pair "grape" -> 4 to the map. Finally, we remove the "orange" key and its associated value from the map.

updating mutable and immutable map in scala

Adding New Key-Value Pair

Adding a New Key-Value Pair in a Mutable Map:

To add a new key-value pair to a mutable map in Scala, we can use the += operator or the put method.

Example:

In the example above, we first create a mutable map myMutableMap with two key-value pairs ("apple" -> 1 and "banana" -> 2). Then, we add two new key-value pairs: "orange" -> 3 using the += operator and "grape" -> 4 using the put method.

Adding a New Key-Value Pair in an Immutable Map:

Since immutable maps are not modifiable, to add a new key-value pair we create a new map with the additional key-value pair. The original map remains unchanged.

Example:

In the example above, we first create an immutable map myImmutableMap with two key-value pairs ("apple" -> 1 and "banana" -> 2). Then, we create a new map updatedMap with an additional key-value pair "orange" -> 3 using the + operator. Alternatively, we create a new map newImmutableMap with the "grape" -> 4 key-value pair using the updated method.

Deleting a Key-Value Pair

We can delete a key-value pair from a map in Scala using both mutable and immutable map variants. The approach for each type of map differs:

Deleting a Key-Value Pair in a Mutable Map:

To delete a key-value pair from a mutable map, we can use the -= operator or the remove method.

Example:

In the example above, we first create a mutable map myMutableMap with three key-value pairs ("apple" -> 1, "banana" -> 2, and "orange" -> 3). Then, we delete the key-value pair with the key "banana" using the -= operator and remove the key-value pair with the key "orange" using the remove method.

Deleting a Key-Value Pair in an Immutable Map:

Since immutable maps are not modifiable, we can create a new map without the specified key, which effectively deletes the key-value pair from the original map.

Example:

In the example above, we first create an immutable map myImmutableMap with three key-value pairs ("apple" -> 1, "banana" -> 2, and "orange" -> 3). Then, we create a new map updatedMap without the key-value pair associated with the key "banana" using the - operator. Alternatively, we create a new map newImmutableMap without the key-value pair associated with the key "orange" using the - method.

Iteration in a Map

In Scala, we can iterate over the key-value pairs in a map using various methods. Here are some common ways to iterate through a map:

  • For-Each Loop:
    This method uses the foreach method available on Scala maps to iterate over each key-value pair. By using pattern matching in the foreach block, we can easily extract and use both the key and the value.

    Example:

  • For Loop:
    This approach uses a for loop to iterate through the key-value pairs in the map. We use tuple unpacking to extract the key and value from each iteration.

    Example:

  • Using Map's keySet and Values:
    In this method, we first iterate through the keys of the map using myMap.keySet. Then, for each key, we retrieve the corresponding value using myMap(key).

    Example:

Empty Map

An empty map in Scala is a map collection that contains no key-value pairs. It is essentially a map with zero elements. An empty map is often used as a starting point to which key-value pairs can be added later.

An empty map in scala is created by using the empty keyword while instance initialization of map.

Empty Mutable Map:

Empty Immutable Map:

Mutable vs Immutable Maps

Here are the key differences between mutable and immutable maps:

BasisMutable MapsImmutable Maps
MutabilityThey allow us to add, update, and remove elements after their creation.They are read-only and cannot be changed after their creation.
Insertion/ Deletion PerformanceBecause they can modify the map in place, they have constant or near-constant time complexity (O(1)) on average.Being read-only, they create a new map with the modified content, resulting in a time complexity of O(log n) for tree-based and O(n) for hash-based immutable maps.
Lookup/ Retrieval PerformanceThey offer excellent performance for lookup and retrieval operations, with constant or near-constant time complexity (O(1)) on averageThey also provide good performance for lookup and retrieval, with time complexity of O(log n) for tree-based immutable maps and O(1) for hash-based immutable maps
Concurrency and Thread SafetyMultiple threads accessing the same mutable map without proper synchronization can lead to data corruption and concurrency issues, making mutable maps inherently non-thread-safe.They are inherently thread-safe since they cannot be modified after creation. This makes them ideal for concurrent programming as multiple threads can read from the map without the risk of concurrent modifications.
Memory OverheadThey have lower memory overhead since they can modify the map in place.They have a higher memory overhead because each modification creates a new copy of the map.

Benefits of Using Immutable Maps:

  1. Immutable maps are inherently thread-safe, preventing concurrent modifications and data corruption in multi-threaded environments.
  2. They offer a fixed state, ensuring predictability, reducing bugs, and enhancing code clarity.
  3. Immutable maps enable the safe sharing of data across codebase sections, eliminating accidental modifications.

Conclusion

  • Map in Scala is a collection that associates unique keys with corresponding values, providing an efficient way to store and retrieve data based on keys. It represents a set of key-value pairs where each key maps to exactly one value.
  • In Scala, we can create maps using either the mutable or immutable variants. For mutable maps, import scala.collection.mutable.Map, and for immutable maps, import scala.collection.immutable.Map.
  • Scala maps support various operations to manipulate and access key-value pairs efficiently. Common operations include keys, values, isEmpty, size, contains, get etc.
  • In Scala, mutable maps allow direct value updates using myMap(key) = newValue, while immutable maps create a new map with updates, like updatedMap = myImmutableMap.updated(key, newValue) due to their immutability.
  • Scala offers various methods like foreach and for loops to iterate through key-value pairs in maps.
  • An empty map in Scala contains zero key-value pairs and can be created using the empty keyword.