How to use Scala HashMap Collection

 67 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn How to use Scala HashMap collection with detail examples of each operation.

So before learning about Scala HashMap, we will first understand the basics of a Map.

Scala Map

  1. Map is a collection of key and value pairs. It stores two values: one key and a value.
  2. Scala provides two variants of Map:
    1. Mutable map
    2. Immutable map(default)
  3. Key should always be unique and it cannot have duplicates.
  4. Value can be duplicates.
  5. Value will always be assigned to a Key.
  6. Scala map is similar to java map but syntax differs.
  7. Immutable Map allows us to apply a function on Map but resulting in the creation of a new Map every time. It doesn’t allow us to change the source. On the other hand, the mutable Map allows modifying the source itself.

 

Scala HashMap

  1. HashMap is based on the basic Map implementation, but it uses HashCode to insert and delete data.
  2. HashMap is very faster in terms of insertion and deletion as it uses HashCode to insert the key and value pair.
  3. Order of insertion will not be maintained.

 

Now you have learned HashMap and let us now dive in to coding examples and how to use Scala HashMap.

Objective

  • How to create a HashMap?
  • How to get the size of a HashMap?
  • How to access each elements?
  • How to iterate a HashMap using for comprehension?
  • How to iterate a HashMap using foreach()?
  • How to iterate only keys of a HashMap?
  • How to iterate only values of a HashMap?
  • How to get the head element?
  • How to get the tail element?
  • How to add an element in HashMap?
  • How to remove an element from HashMap?
  • How to add/merge multiple HashMap?

Create a HashMap

In this example, I have created an immutable HashMap with key and value pairs.

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    for ((k, v) <- map) {
      println(k + " ->" + v)
    }
  }
}



================
Output
5 ->subscribe
1 ->staticreference
2 ->like
3 ->share
4 ->feedback

Get the Size of the HashMap

HashMap as a default method size() to get the size.

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    println(map.size)
  }
}


================
Output
5

Access each element of a HashMap

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    println(map(1))
    println(map(3))
    println(map(4))
    println(map(2))
  }
}


==========
Output
staticreference
share
feedback
like

Iterate the HashMap using for

We will use for comprehension to iterate over the elements of HashMap.

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    for ((key, value) <- map) {
      println("key ,value => " + key + " , " + value)
    }
  }
}


============
Output
key ,value => 5 , subscribe
key ,value => 1 , staticreference
key ,value => 2 , like
key ,value => 3 , share
key ,value => 4 , feedback

Iterate the HashMap using foreach

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    map.foreach {
      case (key, value) =>
        println(key);
        println(value)
    }
  }
}



===============
Output
5
subscribe
1
staticreference
2
like
3
share
4
feedback

Iterate only keys of a HashMap

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    map.keys.foreach(println _)
  }
}


=============
Output
5
1
2
3
4

Iterate only values of a HashMap

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    map.values.foreach(println _)
  }
}

=======
Output
subscribe
staticreference
like
share
feedback

Get Head element

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    println(map.head)
  }
}

============
Output
(5,subscribe)

Get Tail element

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //print
    println(map.tail)
  }
}


===========
Output
Map(1 -> staticreference, 2 -> like, 3 -> share, 4 -> feedback)

Add a key-value pair or an element to the HashMap

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //add
    map.+=(10 -> "contact")

    //print
    for ((k, v) <- map) {
      println(k + " ->" + v)
    }
  }
}


============
Output
5 ->subscribe
10 ->contact
1 ->staticreference
2 ->like
3 ->share
4 ->feedback

Remove an element from the map

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    //remove
    map.-=(1)
    map.-=(2)

    //print
    for ((k, v) <- map) {
      println(k + " ->" + v)
    }
  }
}


=========
Output
5 ->subscribe
3 ->share
4 ->feedback

Add/merge multiple maps

/**
 * How to use Scala HashMap Collection
 */
package com.scala

import java.io.PrintWriter
import java.io.File
import java.io.FileWriter
import scala.collection.immutable.HashMap

object StaticReference {

  def main(args: Array[String]): Unit = {

    //create a HashMap
    var map = HashMap(1 -> "staticreference", 2 -> "like", 3 -> "share", 4 -> "feedback", 5 -> "subscribe")

    var map2 = HashMap(11 -> "abc", 12 -> "xyz", 2 -> "merge")

    //add/merge

    map.++=(map2)

    //print
    for ((k, v) <- map) {
      println(k + " ->" + v)
    }
  }
}


============
Output
5 ->subscribe
1 ->staticreference
2 ->merge
12 ->xyz
3 ->share
11 ->abc
4 ->feedback

References: 

I hope you like this tutorial and you were able to understand How to use Scala HashMap collection.

Thanks for reading and please give us a thumb up and comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.