Scala Collections – HashMap

Scala Collections - HashMap

This topic is about Scala Collections – HashMap.

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. HashMap implements immutable map and uses hash table to implement the same.

Declaring HashMap Variables

The following is the syntax for declaring an HashMap variable.

Syntax

val colors = HashMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")

Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following −

Command

var myMap1: HashMap[Char, Int] = colors + ("black" -> "#000000");

Processing HashMap

Below is an example program of showing how to create, initialize and process HashMap −

Example

import scala.collection.immutable.HashMap
object Demo {
   def main(args: Array[String]) = {
      var myMap: HashMap[String,String] = HashMap(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      );
      // Add an element
      var myMap1: HashMap[String,String] = myMap + ("white" -> "#FFFFFF");
      // Print key values
      myMap.keys.foreach{ 
         i =>  
         print( "Key = " + i )
         println(" Value = " + myMap(i) )
      }
      if( myMap.contains( "red" )) {
         println("Red key exists with value :"  + myMap("red"))
      } else {
         println("Red key does not exist")
      }
      if( myMap.contains( "maroon" )) {
         println("Maroon key exists with value :"  + myMap("maroon"))
      } else {
         println("Maroon key does not exist")
      }
      //removing element
      var myMap2: HashMap[String,String] = myMap - ("white");
      // Create empty map
      var myMap3: HashMap[String,String] = HashMap.empty[String, String];
      println(myMap1);
      println(myMap2);
      println(myMap3);		  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Key = azure Value = #F0FFFF
Key = peru Value = #CD853F
Key = red Value = #FF0000
Red key exists with value :#FF0000
Maroon key does not exist
HashMap(azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF, red -> #FF0000)
HashMap(azure -> #F0FFFF, peru -> #CD853F, red -> #FF0000)
HashMap()

In this topic we learned about Scala Collections – HashMap. To learn more, Click Here.

Leave a Reply