Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
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.
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
.
import scala.collection.immutable.HashMap val map = HashMap("a" -> 1, "b" -> 2, "c" -> 3)
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
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 hash maps allow in-place modifications. They reside in the scala.collection.mutable
package.
import scala.collection.mutable.HashMap val mutableMap = HashMap("x" -> 10, "y" -> 20)
val xValue = mutableMap("x") // returns 10
You can modify the map in-place:
mutableMap("x") = 100 // updates the value associated with key "x" mutableMap += ("z" -> 30) mutableMap -= "y"
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 }
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.
Creating and initializing HashMap in Scala:
HashMap
companion object or through mutable and immutable variations.// Immutable HashMap val immutableMap = Map("a" -> 1, "b" -> 2) // Mutable HashMap import scala.collection.mutable.HashMap val mutableMap = HashMap("x" -> 10, "y" -> 20)
Scala mutable and immutable HashMap:
// Immutable HashMap val immutableMap = Map("a" -> 1, "b" -> 2) // Mutable HashMap import scala.collection.mutable.HashMap val mutableMap = HashMap("x" -> 10, "y" -> 20)
HashMap operations in Scala:
+
, -
, ++
, --
, and more for modification.val map = Map("a" -> 1, "b" -> 2) val updatedMap = map + ("c" -> 3)
Adding and removing elements from HashMap in Scala:
+
and removed using -
operations.val map = Map("a" -> 1, "b" -> 2) val updatedMap = map + ("c" -> 3) val removedMap = updatedMap - "b"
Accessing values in Scala HashMap:
val map = Map("a" -> 1, "b" -> 2) val valueA = map("a") // Accessing value for key "a"
Iterating over HashMap in Scala:
foreach
, for
, or other iteration methods.val map = Map("a" -> 1, "b" -> 2) map.foreach { case (key, value) => println(s"Key: $key, Value: $value") }
Updating values in Scala HashMap:
+
operation with an existing key.val map = Map("a" -> 1, "b" -> 2) val updatedMap = map + ("a" -> 3) // Updating value for key "a"
Scala HashMap vs. other collection types:
val list = List("a", "b", "c") val set = Set("x", "y", "z")
Pattern matching with HashMap in Scala:
val map = Map("a" -> 1, "b" -> 2) map.foreach { case (key, value) => println(s"Key: $key, Value: $value") }
Default values and options in Scala HashMap:
get
with Option
can handle non-existing keys in HashMaps.val map = Map("a" -> 1, "b" -> 2) val valueA = map.getOrElse("a", 0) // Using default value val valueCOption = map.get("c") // Using Option
Scala HashMap with case classes:
case class Person(name: String, age: Int) val personMap = Map("Alice" -> Person("Alice", 25), "Bob" -> Person("Bob", 30))