Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

HashMap in Scala

In Scala, a HashMap is a part of the Collections library which provides a mutable and immutable version of hash-based maps. They allow you to store key-value pairs and provide constant-time average performance for most operations.

Immutable HashMap

By default, when you work with a HashMap in Scala, you're working with an immutable version. This means that once a HashMap is created, it can't be changed. Any operation that seems to modify it will actually return a new HashMap.

Importing and Creating:

import scala.collection.immutable.HashMap

val map = HashMap("a" -> 1, "b" -> 2, "c" -> 3)

Accessing Values:

val aValue = map("a")  // returns 1

If a key doesn't exist, it will throw an exception. To safely get a value, use get:

val dValue = map.get("d")  // returns Option[Int], None in this case

Adding and Removing Entries:

Since this is an immutable map, the original map remains unchanged, but a new map is returned.

val newMap = map + ("d" -> 4)
val reducedMap = map - "a"

Mutable HashMap

Mutable hash maps allow in-place modifications. They reside in the scala.collection.mutable package.

Importing and Creating:

import scala.collection.mutable.HashMap

val mutableMap = HashMap("x" -> 10, "y" -> 20)

Accessing Values:

val xValue = mutableMap("x")  // returns 10

Modifying:

You can modify the map in-place:

mutableMap("x") = 100  // updates the value associated with key "x"
mutableMap += ("z" -> 30)
mutableMap -= "y"

Common Operations

Here are some common operations that work on both mutable and immutable versions:

  • Check if a key exists: map.contains("a")

  • Iterate over a HashMap:

    for ((key, value) <- map) {
      println(s"Key: $key, Value: $value")
    }
    
  • Map size: map.size

  • Filtering:

    val filtered = map.filter { case (key, value) => value > 1 }
    

Conclusion

While the immutable HashMap is the default and preferred in functional programming scenarios, the mutable HashMap is also available for situations where in-place modifications are more efficient or convenient. Always think about which version better suits your needs based on the context of your application.

  1. Creating and initializing HashMap in Scala:

    • Description: HashMaps can be created and initialized using the HashMap companion object or through mutable and immutable variations.
    • Code Example:
      // Immutable HashMap
      val immutableMap = Map("a" -> 1, "b" -> 2)
      
      // Mutable HashMap
      import scala.collection.mutable.HashMap
      val mutableMap = HashMap("x" -> 10, "y" -> 20)
      
  2. Scala mutable and immutable HashMap:

    • Description: Immutable HashMaps cannot be modified after creation, while mutable HashMaps support dynamic changes.
    • Code Example:
      // Immutable HashMap
      val immutableMap = Map("a" -> 1, "b" -> 2)
      
      // Mutable HashMap
      import scala.collection.mutable.HashMap
      val mutableMap = HashMap("x" -> 10, "y" -> 20)
      
  3. HashMap operations in Scala:

    • Description: HashMaps support various operations like +, -, ++, --, and more for modification.
    • Code Example:
      val map = Map("a" -> 1, "b" -> 2)
      val updatedMap = map + ("c" -> 3)
      
  4. Adding and removing elements from HashMap in Scala:

    • Description: Elements can be added using + and removed using - operations.
    • Code Example:
      val map = Map("a" -> 1, "b" -> 2)
      val updatedMap = map + ("c" -> 3)
      val removedMap = updatedMap - "b"
      
  5. Accessing values in Scala HashMap:

    • Description: Values in HashMaps can be accessed using the key.
    • Code Example:
      val map = Map("a" -> 1, "b" -> 2)
      val valueA = map("a") // Accessing value for key "a"
      
  6. Iterating over HashMap in Scala:

    • Description: HashMaps can be iterated using foreach, for, or other iteration methods.
    • Code Example:
      val map = Map("a" -> 1, "b" -> 2)
      map.foreach { case (key, value) =>
        println(s"Key: $key, Value: $value")
      }
      
  7. Updating values in Scala HashMap:

    • Description: Values in HashMaps can be updated using the + operation with an existing key.
    • Code Example:
      val map = Map("a" -> 1, "b" -> 2)
      val updatedMap = map + ("a" -> 3) // Updating value for key "a"
      
  8. Scala HashMap vs. other collection types:

    • Description: HashMaps provide fast key-based access, but other collection types may be preferred based on specific use cases.
    • Code Example:
      val list = List("a", "b", "c")
      val set = Set("x", "y", "z")
      
  9. Pattern matching with HashMap in Scala:

    • Description: Pattern matching can be used to destructure and extract values from HashMap entries.
    • Code Example:
      val map = Map("a" -> 1, "b" -> 2)
      map.foreach {
        case (key, value) => println(s"Key: $key, Value: $value")
      }
      
  10. Default values and options in Scala HashMap:

    • Description: Default values or get with Option can handle non-existing keys in HashMaps.
    • Code Example:
      val map = Map("a" -> 1, "b" -> 2)
      val valueA = map.getOrElse("a", 0) // Using default value
      val valueCOption = map.get("c")    // Using Option
      
  11. Scala HashMap with case classes:

    • Description: HashMaps can be used effectively with case classes for structured data storage.
    • Code Example:
      case class Person(name: String, age: Int)
      
      val personMap = Map("Alice" -> Person("Alice", 25), "Bob" -> Person("Bob", 30))