Scala – Map

  • date 8th October, 2020 |
  • by Prwatech |
  • 0 Comments

Map:

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. Maps are also called Hash tables. There are two kinds of Maps, the immutable and the mutable.

It is a universal concept, where it deals with Key-Value pair.

The fastest searching algorithm.

use case 1:

package Collection
class Map1 {

  val m = Map(1 -> "Python", 2 -> "Scala", 3 -> "Hadoop")
  val m1 = Map((91,"Ind"), (7,"USA"), (37,"USSR"))
  def courses(): Unit = {
    println(m.get(2))
    println(m.keys)
    println(m.values)
  }
}
object ME{
  def main(args:Array[String]):Unit = {
    new Map1().courses()
    println("Maps is implemented")
  }
}

use case 2:

scala> val mapping = Map("Prwa" -> "Tech","Hadoop" -> "Developer","Spark" -> "Scala")

scala> val mapping = scala.collection.mutable.Map("Mysql" -> "S","Linux" -> "L","Python" -> "P")

scala> val x = mapping("Mysql")

scala> val x = mapping("Linux")

scala> val x = mapping("Python")

scala> for((s,l) <- mapping) yield(l,s)

use case 3:

scala> val mapping = Map("Tom" -> "Hardy","Christian" -> "Bale")

scala>  val mapping = scala.collection.mutable.Map("Leonardo" -> "D","Brad" -> "B")

scala> val x = mapping("Tom")

//Accessing maps

Contd..

scala> val mapping = Map("Tom" -> "Hardy","Christian" -> "Bale")

scala>  val mapping = scala.collection.mutable.Map("Leonardo" -> "D","Brad" -> "B")

scala> val x = mapping("Leonardo")

#Iterating Maps:

scala> for((d,b) <- mapping) yield(b,d)

Quick Support

image image