Introduction to Scala Maps

If Your are interested to learn about the Scala Final Variables

Map is used to store elements. It stores elements in pairs of key and values. In scala, you can create map by using two ways either by using comma separated pairs or by using rocket operator.

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. The difference between mutable and immutable objects is that when an object is immutable, the object itself can’t be changed.

By default, Scala uses the immutable Map. If you want to use the mutable Map, you’ll have to import scala.collection.mutable.Map class explicitly. If you want to use both mutable and immutable Maps in the same, then you can continue to refer to the immutable Map as Map but you can refer to the mutable set as mutable.Map.

Scala Maps Example

In the following example, we have both approaches to create map.

object MainObject{  
    def main(args:Array[String]){  
        var map = Map(("A","Apple"),("B","Ball"))  
        var map2 = Map("A"->"Aple","B"->"Ball")  
        var emptyMap:Map[String,String] = Map.empty[String,String]   
        println(map)  
        println(map2)  
        println("Empty Map: "+emptyMap)  
    }  
}  <a href="https://www.javatpoint.com/scala-maps#"></a><a href="https://www.javatpoint.com/scala-maps#"></a><a href="https://www.javatpoint.com/scala-maps#"></a>

Output:

Map(A -> Apple, B -> Ball)
Map(A -> Aple, B -> Ball)
Empty Map: Map()

Scala Map Example: Adding and Removing Elements

You can add and remove new elements in maps. Scala provides you lots of predefined method. You can use them to perform operations on the Maps. In the following example, we have created a new Map.Play Video

object MainObject{  
    def main(args:Array[String]){  
        var map = Map(("A","Apple"),("B","Ball"))  
        var map2 = Map("A"->"Aple","B"->"Ball")  
        var emptyMap:Map[String,String] = Map.empty[String,String]   
        println(map)  
        println(map2)  
        println("Empty Map: "+emptyMap)  
    }  
}  <a href="https://campaign.adpushup.com/get-started/?utm_source=banner&amp;utm_campaign=growth_hack" target="_blank" rel="noreferrer noopener"></a>

Output:

Apple
Map(A -> Apple, B -> Ball, C -> Cat)
Map(A -> Apple, C -> Cat)

Basic Operations on MAP

All operations on maps can be expressed in terms of the following three methods.

Sr.NoMethods & Description
1keysThis method returns an iterable containing each key in the map.
2valuesThis method returns an iterable containing each value in the map.
3isEmptyThis method returns true if the map is empty otherwise false.

Try the following example program showing usage of the Map methods.

Example

object Demo {
   def main(args: Array[String]) {
      val colors = Map("red" -&gt; "#FF0000", "azure" -&gt; "#F0FFFF", "peru" -&gt; "#CD853F")

      val nums: Map[Int, Int] = Map()

      println( "Keys in colors : " + colors.keys )
      println( "Values in colors : " + colors.values )
      println( "Check if colors is empty : " + colors.isEmpty )
      println( "Check if nums is empty : " + nums.isEmpty )
   }
}

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

Keys in colors : Set(red, azure, peru)
Values in colors : MapLike(#FF0000, #F0FFFF, #CD853F)
Check if colors is empty : false
Check if nums is empty : true

Concatenating Maps

You can use either ++ operator or Map.++() method to concatenate two or more Maps, but while adding Maps it will remove duplicate keys.Try the following example program to concatenate two Maps.

Example

object Demo {
   def main(args: Array[String]) {
      val colors1 = Map("red" -&gt; "#FF0000", "azure" -&gt; "#F0FFFF", "peru" -&gt; "#CD853F")
      val colors2 = Map("blue" -&gt; "#0033FF", "yellow" -&gt; "#FFFF00", "red" -&gt; "#FF0000")

      // use two or more Maps with ++ as operator
      var colors = colors1 ++ colors2
      println( "colors1 ++ colors2 : " + colors )

      // use two maps with ++ as method
      colors = colors1.++(colors2)
      println( "colors1.++(colors2)) : " + colors )
   }
}

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

colors1 ++ colors2 : Map(blue -> #0033FF, azure -> #F0FFFF, 
   peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)

colors1.++(colors2)) : Map(blue -> #0033FF, azure -> #F0FFFF, 
   peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)

Print Keys and Values from a Map

You can iterate through the keys and values of a Map using “foreach” loop. Here, we used method foreach associated with iterator to walk through the keys. Following is the example program.

Example

object Demo {
   def main(args: Array[String]) {
      val colors = Map("red" -&gt; "#FF0000", "azure" -&gt; "#F0FFFF","peru" -&gt; "#CD853F")

      colors.keys.foreach{ i =&gt;  
         print( "Key = " + i )
         println(" Value = " + colors(i) )}
   }
}

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

Red key exists with value :#FF0000
Maroon key does not exist

Scala Map Methods

Following are the important methods which you can use while playing with Maps. For a complete list of methods available, please check official documentation of Scala.

Sr.NoMethods with Description
1def ++(xs: Map[(A, B)]): Map[A, B]Returns a new map containing mappings of this map and those provided by xs.
2def -(elem1: A, elem2: A, elems: A*): Map[A, B]Returns a new map containing all the mappings of this map except mappings with a key equal to elem1, elem2 or any of elems.
3def –(xs: GTO[A]): Map[A, B]Returns a new map with all the key/value mappings of this map except mappings with a key equal to a key from the traversable object xs.
4def get(key: A): Option[B]Optionally returns the value associated with a key.
5def iterator: Iterator[(A, B)]Creates a new iterator over all key/value pairs of this map
6def addString(b: StringBuilder): StringBuilderAppends all elements of this shrinkable collection to a string builder.
7def addString(b: StringBuilder, sep: String): StringBuilderAppends all elements of this shrinkable collection to a string builder using a separator string.
8def apply(key: A): BReturns the value associated with the given key, or the result of the map’s default method, if none exists.
9def clear(): UnitRemoves all bindings from the map. After this operation has completed, the map will be empty.
10def clone(): Map[A, B]Creates a copy of the receiver object.
11def contains(key: A): BooleanReturns true if there is a binding for key in this map, false otherwise.
12def copyToArray(xs: Array[(A, B)]): UnitCopies values of this shrinkable collection to an array. Fills the given array xs with values of this shrinkable collection.
13def count(p: ((A, B)) => Boolean): IntCounts the number of elements in the shrinkable collection which satisfy a predicate.
14def default(key: A): BDefines the default value computation for the map, returned when a key is not found.
15def drop(n: Int): Map[A, B]Returns all elements except first n ones.
16def dropRight(n: Int): Map[A, B]Returns all elements except last n ones
17def dropWhile(p: ((A, B)) => Boolean): Map[A, B]Drops longest prefix of elements that satisfy a predicate.
18def empty: Map[A, B]Returns the empty map of the same type.
19def equals(that: Any): BooleanReturns true if both maps contain exactly the same keys/values, false otherwise.
20def exists(p: ((A, B)) => Boolean): BooleanReturns true if the given predicate p holds for some of the elements of this shrinkable collection, otherwise false.
21def filter(p: ((A, B))=> Boolean): Map[A, B]Returns all elements of this shrinkable collection which satisfy a predicate.
22def filterKeys(p: (A) => Boolean): Map[A, B]Returns an immutable map consisting only of those key value pairs of this map where the key satisfies the predicate p.
23def find(p: ((A, B)) => Boolean): Option[(A, B)]Finds the first element of the shrinkable collection satisfying a predicate, if any.
24def foreach(f: ((A, B)) => Unit): UnitApplies a function f to all elements of this shrinkable collection.
25def init: Map[A, B]Returns all elements except the last.
26def isEmpty: BooleanTests whether the map is empty.
27def keys: Iterable[A]Returns an iterator over all keys.
28def last: (A, B)Returns the last element.
29def max: (A, B)Finds the largest element.
30def min: (A, B)Finds the smallest element.
31def mkString: StringDisplays all elements of this shrinkable collection in a string.
32def product: (A, B)Returns the product of all elements of this shrinkable collection with respect to the * operator in num.
33def remove(key: A): Option[B]Removes a key from this map, returning the value associated previously with that key as an option.
34def retain(p: (A, B) => Boolean): Map.this.typeRetains only those mappings for which the predicate p returns true.
35def size: IntReturn the number of elements in this map.
36def sum: (A, B)Returns the sum of all elements of this shrinkable collection with respect to the + operator in num.
37def tail: Map[A, B]Returns all elements except the first.
38def take(n: Int): Map[A, B]Returns first n elements.
39def takeRight(n: Int): Map[A, B]Returns last n elements.
40def takeWhile(p: ((A, B)) => Boolean): Map[A, B]Takes longest prefix of elements that satisfy a predicate.
41def toArray: Array[(A, B)]Converts this shrinkable collection to an array.
42def toBuffer[B >: A]: Buffer[B]Returns a buffer containing all elements of this map.
43def toList: List[A]Returns a list containing all elements of this map.
44def toSeq: Seq[A]Returns a seq containing all elements of this map.
45def toSet: Set[A]Returns a set containing all elements of this map.
46def toString(): StringReturns a String representation of the object.
Introduction to Scala Maps
Show Buttons
Hide Buttons