HashMap is a part of Scala Collection’s. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map.
Syntax:
var hashMapName = HashMap("key1"->"value1", "key2"->"value2", "key3"->"value3", ...)
We must import scala.collection.mutable.HashMap
for HashMap.
Operation performed by HashMap
Creating an HashMap:
Below is the example to create HashMap. In below code, we can see an empty HashMap is created then a HashMap is created with values.
import scala.collection.mutable.HashMap
object Geeks
{
def main(args : Array[String])
{
var hashMap = new HashMap()
var hashMap 2 = HashMap( "C" - > "Csharp" , "S" - > "Scala" , "J" - > "Java" )
println(hashMap)
println(hashMap 2 )
}
}
|
Output:
Map()
Map(S -> Scala, J -> Java, C -> Csharp)
Adding and Accessing Elements :
In the below example, A HashMap is created. add elements and access elements also performed.
import scala.collection.mutable.HashMap
object Geeks
{
def main(args : Array[String])
{
var hashMap = HashMap( "C" - > "Csharp" , "S" - > "Scala" , "J" - > "Java" )
hashMap.foreach
{
case (key, value) => println (key + " -> " + value)
}
println(hashMap( "S" ))
var HashMap 2 = hashMap + ( "P" - > "Perl" )
HashMap 2 .foreach
{
case (key, value) => println (key + " -> " + value)
}
}
}
|
Output:
S -> Scala
J -> Java
C -> Csharp
Scala
S -> Scala
P -> Perl
J -> Java
C -> Csharp
Removing an element from HashMap :
A HashMap is created than removing an element is performed using – sign. Below is the example to removing an element from HashMap.
import scala.collection.mutable.HashMap
object Geeks
{
def main(args : Array[String])
{
var hashMap = HashMap( "C" - > "Csharp" , "S" - > "Scala" , "J" - > "Java" )
hashMap.foreach
{
case (key, value) => println (key + " -> " + value)
}
hashMap - = "C"
println( "After Removing" )
hashMap.foreach
{
case (key, value) => println (key + " -> " + value)
}
}
}
|
Output:
S -> Scala
J -> Java
C -> Csharp
After Removing
S -> Scala
J -> Java