Introduction
In Scala, Map is used to store (key,value) pairs. It has the following 3 flavours in Scala API
Just like Strings uses '+' operator for String concatenation, Map uses '++' operator to concatenate two Maps.
NOTE:- If we don't specify the type of Map, Scala Compiler creates Immutable Map automatically.
Let us explore Scala Map with some examples.
- scala.collection.Map
- scala.collection.mutable.Map
- scala.collection.immutable.Map
Based on context, we can use either Mutable or Immutable Map.
Just like Strings uses '+' operator for String concatenation, Map uses '++' operator to concatenate two Maps.
NOTE:- If we don't specify the type of Map, Scala Compiler creates Immutable Map automatically.
Let us explore Scala Map with some examples.
Examples:
To create empty Map
scala> val map1 = Map()
map1: scala.collection.immutable.Map[Nothing,Nothing] = Map()
To create empty Map by specifying key and value types
scala> val map1 = Map[String,String]()
map1: scala.collection.immutable.Map[String,String] = Map()
To create a Map with key and value pair values
scala> val map1 = Map(1 -> "one", 2 -> "two")
map1: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two)
scala> val map1 = Map()
map1: scala.collection.immutable.Map[Nothing,Nothing] = Map()
To create empty Map by specifying key and value types
scala> val map1 = Map[String,String]()
map1: scala.collection.immutable.Map[String,String] = Map()
To create a Map with key and value pair values
scala> val map1 = Map(1 -> "one", 2 -> "two")
map1: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two)
Here Scala compiler will automatically infer the types of (key,value) pair.
To add a new (key,value) pair to existing Map instance
scala> val map1 = Map(1->"one",2->"two")
map1: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two)
scala> val map2 = map1 + (3->"three")
map2: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two, 3 -> three)
scala> map1
res0: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two)
scala> map2
res1: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two, 3 -> three)
No change to map1.
To concatenate two Map instances
map3: scala.collection.immutable.Map[Int,String] = Map(4 -> four, 5 -> five)
scala> val map4 = map2 ++ map3
map4: scala.collection.immutable.Map[Int,String] = Map(5 -> five, 1 -> one, 2 -> two, 3 -> three, 4 -> four)
scala> map4
res2: scala.collection.immutable.Map[Int,String] = Map(5 -> five, 1 -> one, 2 -> two, 3 -> three, 4 -> four)
That's it.
Please drop me your valuable suggestions or comments on my posts.
Thank you.
No comments:
Post a Comment