Home »
Scala
HashMap in Scala
By IncludeHelp Last updated : November 14, 2024
Scala HashMap
HashMap is a collection based on maps and hashes. It stores key-value pairs.
Denoted by
HashMap<Key, Value> or HashMap<K, V>
Syntax
var hashmap = HashMap("key1" -> "value1", ...);
Import HashMap
To import HashMap to our Scala program, the following statement is used,
scala.collection.mutable.HashMap
Now, let's see the operations on HashMap in Scala,
Example 1: Creating HashMap in Scala
Creating a HashMap in Scala is an easy process. A HashMap in Scala can be empty also.
import scala.collection.mutable.HashMap
object MyClass {
def main(args: Array[String]): Unit = {
var hashmap = new HashMap()
var hashmap2 = HashMap(1 -> "K1200" , 2 -> "Thunderbird 350", 3 -> "CBR 1000")
println("Empty HashMap : "+hashmap)
println("Hashmap with elements : "+hashmap2)
}
}
Output
Empty HashMap : HashMap()
Hashmap with elements : HashMap(1 -> K1200, 2 -> Thunderbird 350, 3 -> CBR 1000)
Example 2: Accessing elements of HashMap
The elements of a HashMap can be accessed in Scala using foreach loop as shown below,
import scala.collection.mutable.HashMap
object MyClass {
def main(args: Array[String]): Unit = {
var hashmap = HashMap(1 -> "K1200" , 2 -> "Thunderbird 350", 3 -> "CBR 1000")
hashmap.foreach
{
case (key, value) => println (key + " -> " + value)
}
}
}
Output
1 -> K1200
2 -> Thunderbird 350
3 -> CBR 1000
Example 3: Adding elements to the HashMap
Adding of elements to the HashMap can also be done in Scala programming language. The + operator is used to add new key-value pair to the HashMap.
import scala.collection.mutable.HashMap
object MyClass {
def main(args: Array[String]): Unit = {
var hashmap = HashMap(1 -> "K1200" , 2 -> "Thunderbird 350", 3 -> "CBR 1000")
println("The HashMap is : "+hashmap)
println("Adding new elements to the HashMap. ")
hashmap += (7 -> "HD Fat Boy")
println("The HashMap is : "+hashmap)
}
}
Output
The HashMap is : HashMap(1 -> K1200, 2 -> Thunderbird 350, 3 -> CBR 1000)
Adding new elements to the HashMap.
The HashMap is : HashMap(1 -> K1200, 2 -> Thunderbird 350, 3 -> CBR 1000, 7 -> HD Fat Boy)
Example 4: Removing element from HashMap in Scala
In Scala removing elements from a HashMap is also possible. The - operator is used to remove elements from HashMap.
import scala.collection.mutable.HashMap
object MyClass {
def main(args: Array[String]): Unit = {
var hashmap = HashMap(1 -> "K1200" , 2 -> "Thunderbird 350", 3 -> "CBR 1000")
println("The HashMap is : "+hashmap)
println("removing elements to the HashMap. ")
hashmap -= 3
println("The HashMap is : "+hashmap)
}
}
Output
The HashMap is : HashMap(1 -> K1200, 2 -> Thunderbird 350, 3 -> CBR 1000)
removing elements to the HashMap.
The HashMap is : HashMap(1 -> K1200, 2 -> Thunderbird 350)