Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Scala Map

In Scala, the term "Map" refers to a collection that holds key-value pairs. Maps allow you to associate unique keys with values. They can be mutable or immutable, and Scala's collections library provides implementations for both. By default, when you use the Map class in Scala without an import, you're referring to an immutable Map.

Here's a brief overview:

1. Creating a Map:

  • Immutable Map:

    val immutableMap = Map("John" -> 25, "Doe" -> 30)
    
  • Mutable Map:

    You first need to import the mutable Map class.

    import scala.collection.mutable.Map
    
    val mutableMap = Map("John" -> 25, "Doe" -> 30)
    

2. Accessing Values:

To get the value associated with a particular key:

val age = immutableMap("John")  // returns 25

If you access a key that doesn't exist, it will throw a NoSuchElementException. To safely retrieve values, you can use the get method which returns an Option:

val ageOption = immutableMap.get("Alice")  // returns None since "Alice" doesn't exist

3. Adding and Removing Entries:

  • Immutable Map:

    When you "add" to an immutable map, you're actually creating a new map:

    val newMap = immutableMap + ("Alice" -> 28)
    
  • Mutable Map:

    You can add or remove entries directly:

    mutableMap("Alice") = 28  // adding
    mutableMap -= "John"      // removing
    

4. Iterating Over a Map:

You can iterate over both keys and values:

for ((name, age) <- immutableMap) {
  println(s"$name is $age years old")
}

5. Useful Map Operations:

  • keys: Returns all keys.
  • values: Returns all values.
  • isEmpty: Checks if the map is empty.
  • contains: Checks if the map contains a key.

6. Merging Maps:

You can merge two maps. In case of key collisions, the keys from the second map will overwrite those from the first:

val map1 = Map("a" -> 1, "b" -> 2)
val map2 = Map("b" -> 3, "c" -> 4)

val merged = map1 ++ map2  // Result: Map(a -> 1, b -> 3, c -> 4)

Summary:

Maps are fundamental data structures in Scala and most programming languages. Scala offers both mutable and immutable versions, and the choice between them depends on your specific use case. However, it's generally recommended to use immutable collections in Scala, as they offer better safety, especially in concurrent environments.

  1. Creating and Initializing Maps in Scala:

    Initialize a Map using the Map constructor.

    val myMap: Map[String, Int] = Map("one" -> 1, "two" -> 2, "three" -> 3)
    
  2. Mutable vs Immutable Maps in Scala:

    • Immutable Map:

      val immutableMap = Map("one" -> 1, "two" -> 2)
      
    • Mutable Map:

      import scala.collection.mutable.Map
      
      val mutableMap = Map("one" -> 1, "two" -> 2)
      
  3. Accessing and Updating Values in Scala Map:

    val valueForKey = myMap("two")
    val updatedMap = myMap + ("four" -> 4)
    
  4. Iterating Over Keys and Values in Scala Map:

    for ((key, value) <- myMap) {
      println(s"Key: $key, Value: $value")
    }
    
  5. Common Map Operations in Scala:

    • Getting Keys:

      val keys = myMap.keys
      
    • Getting Values:

      val values = myMap.values
      
    • Checking for Key:

      val containsKey = myMap.contains("three")
      
  6. Pattern Matching with Maps in Scala:

    val result = myMap match {
      case m if m.contains("one") => "Contains 'one'"
      case _ => "Does not contain 'one'"
    }
    
  7. Filtering and Transforming Maps in Scala:

    val filteredMap = myMap.filter { case (_, value) => value > 1 }
    val transformedMap = myMap.map { case (key, value) => key -> (value * 2) }
    
  8. Working with Nested Maps in Scala:

    val nestedMap = Map("outer" -> Map("inner" -> 42))
    
    val innerValue = nestedMap.get("outer").flatMap(_.get("inner"))