Learn Scala Map with Examples Quickly & Effectively
1. Scala Map – Objective
In this tutorial on Scala Map, we will see how to define and process maps, and what methods to call on them. We will learn to declare a Scala Map, Operations on a Map in Scala, Concatenating Maps, Printing Keys and Values from a Scala Map, Searching for a Key in a Map, Methods to Call on a Map etc.
So, let’s begin Scala Map Tutorial.
2. An Introduction to Maps in Scala
A Map in Scala is a collection of key-value pairs, and is also called a hash table. We can use a key to access a value. These keys are unique; however, the values may be common. The default Scala Map is immutable. To use a mutable Map, we use the scala.collection.mutable.Map class. To use both in the same place, refer to the immutable Map as Map, and to the mutable Map as mutable.Map. I also recommend you refer our latest blog on Scala Closures which is explained in detail with Examples. For now let’s jump to learn to declare a Scala Map.
3. Declaring a Scala Map
We can either declare an empty Scala map or one with values.
a. Declaring an Empty Scala Map
scala> var m:Map[String,Int]=Map() m: Map[String,Int] = Map()
Here, we must include the type annotation so it can assign proper types to the variables.
b. Declaring a Scala Map with Values
When we provide values, Scala will use those to infer the type of variables. So, we don’t need to include the type annotations.
scala> var m=Map("Ayushi"->0,"Megha"->1) m: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0, Megha -> 1)
Now, to add a key-value pair to this, we do the following:
scala> m+=("Ruchi"->2) scala> m res1: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0, Megha -> 1, Ruchi -> 2)
Learn: Scala Arrays and Multidimensional Arrays in Scala
4. Operations on a Map in Scala
These are the basic operations we can carry out on a Map:
a. keys
This returns an iterable with each key in the Map.
scala> m.keys res2: Iterable[String] = Set(Ayushi, Megha, Ruchi) scala> m("Megha") res56: Int = 1
b. values
This returns an iterable with each value in the Scala Map.
scala> m.values res3: Iterable[Int] = MapLike.DefaultValuesIterable(0, 1, 2)
c. isEmpty
If the Map is empty, this returns true; otherwise, false.
scala> m.isEmpty res4: Boolean = false scala> Map().isEmpty res5: Boolean = true
5. Concatenating Maps in Scala
We can concatenate/joing two Maps in more than one way. Let’s take another Scala Map for this.
scala> var m1=Map("Megha"->3,"Ruchi"->2,"Becky"->4) m1: scala.collection.immutable.Map[String,Int] = Map(Megha -> 3, Ruchi -> 2, Becky -> 4)
The ++ Operator
scala> m++m1 res6: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0, Megha -> 3, Ruchi -> 2, Becky -> 4) scala> m1++m res7: scala.collection.immutable.Map[String,Int] = Map(Megha -> 1, Ruchi -> 2, Becky -> 4, Ayushi -> 0)
See the difference in the values for “Megha” in both cases?
Learn: Scala Operator
6. Printing Keys and Values from a Map
We can use a foreach loop to walk through the keys and values of a Scala Map:
scala> m.keys.foreach{i=>println(i+" "+m(i))}
Ayushi 0
Megha 1
Ruchi 2
7. Searching for a Key in a Scala Map
The Map.contains() method will tell us if a certain key exists in the Map.
scala> m.contains("Ayushi") res10: Boolean = true scala> m.contains("Fluffy") res11: Boolean = false
Any Doubt yet in Scala Map? Please Comment.
8. Methods to Call on a Scala Map
We can call the following methods on a Map. (Note that they don’t modify the original Scala Map)
a. def ++(xs: Map[(A, B)]): Map[A, B]
This concatenates two Maps.
scala> m.++(m1) res15: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0, Megha -> 3, Ruchi -> 2, Becky -> 4) scala> m1.++(m) res16: scala.collection.immutable.Map[String,Int] = Map(Megha -> 1, Ruchi -> 2, Becky -> 4, Ayushi -> 0)
b. def -(elem1: A, elem2: A, elems: A*): Map[A, B]
This returns a new Map eliding the pairs for the keys mentioned in the arguments.
scala> m.-("Ayushi","Ruchi") res21: scala.collection.immutable.Map[String,Int] = Map(Megha -> 1)
c. def get(key: A): Option[B]
This returns the value associated with the key; it returns this as an Option.
scala> m.get("Megha") res27: Option[Int] = Some(1) scala> m.get("Fluffy") res28: Option[Int] = None
d. def iterator: Iterator[(A, B)]
This returns an iterator over the Scala Map.
scala> m.iterator res29: Iterator[(String, Int)] = non-empty iterator
Learn: Scala Arrays and Multidimensional Arrays in Scala
e. def addString(b: StringBuilder): StringBuilder
This appends all elements of the Map to the String Builder.
scala> m.addString(new StringBuilder()) res30: StringBuilder = Ayushi -> 0Megha -> 1Ruchi -> 2
f. def addString(b: StringBuilder, sep: String): StringBuilder
This does what the above method does, except it introduces a separator between the pairs.
scala> m.addString(new StringBuilder(),"*") res31: StringBuilder = Ayushi -> 0*Megha -> 1*Ruchi -> 2
g. def apply(key: A): B
This searches for a key in the Scala Map.
scala> m.apply("Fluffy") java.util.NoSuchElementException: key not found: Fluffy at scala.collection.immutable.Map$Map3.apply(Map.scala:167) ... 28 elided scala> m.apply("Ayushi") res33: Int = 0
h. def clear(): Unit
This actually removes all bindings from the Map in Scala.
scala> import scala.collection.mutable.Map import scala.collection.mutable.Map scala> var m2=scala.collection.mutable.Map("One"->1,"Two"->2,"Three"->3) m2: scala.collection.mutable.Map[String,Int] = Map(One -> 1, Two -> 2, Three -> 3) scala> m2.clear() scala> m2 res36: scala.collection.mutable.Map[String,Int] = Map()
Doing this to m1 will result in the following error:
scala> m1.clear() <console>:13: error: value clear is not a member of scala.collection.immutable.Map[String,Int] m1.clear() ^
i. def clone(): Map[A, B]
This creates a clone/copy of the receiver object.
We can’t clone an immutable Map in Scala. So, let’s revive m2.
scala> var m2=scala.collection.mutable.Map("One"->1,"Two"->2,"Three"->3) m2: scala.collection.mutable.Map[String,Int] = Map(One -> 1, Two -> 2, Three -> 3) scala> m2.clone() res38: scala.collection.mutable.Map[String,Int] = Map(One -> 1, Two -> 2, Three -> 3)
j. def contains(key: A): Boolean
If the Map contains this key, this returns true; otherwise, false.
scala> m.contains("Megha") res40: Boolean = true scala> m.contains("Fluffy") res41: Boolean = false
k. def copyToArray(xs: Array[(A, B)]): Unit
This fills key-value pairs from the Map into an Array.
scala> var arr:Array[Any]=Array(0,0,0,0,0,0,0,0) arr: Array[Any] = Array(0, 0, 0, 0, 0, 0, 0, 0) scala> m.copyToArray(arr) scala> arr res47: Array[Any] = Array((Ayushi,0), (Megha,1), (Ruchi,2), 0, 0, 0, 0, 0)
l. def count(p: ((A, B)) => Boolean): Int
This returns the number of key-value pairs in the Scala Map that satisfy the given predicate.
scala> m.count(x=>true) res49: Int = 3
Learn: Tuples in Scala – A Quick and Easy Tutorial
m. def drop(n: Int): Map[A, B]
This returns all elements except the first n.
scala> m.drop(2) res59: scala.collection.immutable.Map[String,Int] = Map(Ruchi -> 2)
n. def dropRight(n: Int): Map[A, B]
This returns all elements except the last n.
scala> m.dropRight(2) res60: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0)
o. def dropWhile(p: ((A, B)) => Boolean): Map[A, B]
This drops pairs until the predicate becomes false for a pair.
scala> m.dropWhile(x=>false) res61: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0, Megha -> 1, Ruchi -> 2)
p. def empty: Map[A, B]
This returns an empty Map of the same kind.
scala> m.empty res68: scala.collection.immutable.Map[String,Int] = Map()
q. def equals(that: Any): Boolean
This returns true if both Maps contain the same key-value pairs; otherwise, false.
scala> m.equals(m1) res69: Boolean = false
r. def exists(p: ((A, B)) => Boolean): Boolean
If the predicate holds true for some elements of the Scala Map, this returns true; otherwise, false.
s. def filter(p: ((A, B))=> Boolean): Map[A, B]
This returns all such elements (see above).
t. def filterKeys(p: (A) => Boolean): Map[A, B]
This returns all pairs where the key satisfies the predicate.
u. def find(p: ((A, B)) => Boolean): Option[(A, B)]
This returns the first element that satisfies the predicate.
v. def foreach(f: ((A, B)) => Unit): Unit
This applies the function to all elements of the Scala Map.
w. def init: Map[A, B]
This returns all elements except the last.
scala> m.init res82: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0, Megha -> 1)
x. def isEmpty: Boolean
If the Map is empty, this returns true; otherwise, false.
scala> m.isEmpty res83: Boolean = false
y. def keys: Iterable[A]
This returns an iterator over all keys in the Map.
scala> m.keys res84: Iterable[String] = Set(Ayushi, Megha, Ruchi)
z. def last: (A, B)
This returns the last element from the Map in Scala.
scala> m.last res85: (String, Int) = (Ruchi,2)
aa. def max: (A, B)
This returns the largest element.
scala> m.max res86: (String, Int) = (Ruchi,2)
ab. def min: (A, B)
This returns the smallest element.
scala> m.min res87: (String, Int) = (Ayushi,0)
ac. def mkString: String
This represents the elements of the Map as a String.
scala> m.mkString res88: String = Ayushi -> 0Megha -> 1Ruchi -> 2
ad. def product: (A, B)
This returns the product of all elements of the Scala Map.
ae. def remove(key: A): Option[B]
This removes a key from the Map and returns the value. Let’s take a new Map for this.
scala> var d=Map(1->2,3->4,5->6) d: scala.collection.mutable.Map[Int,Int] = Map(5 -> 6, 1 -> 2, 3 -> 4) scala> d.remove(3) res93: Option[Int] = Some(4)
af. def retain(p: (A, B) => Boolean): Map.this.type
This retains, in the Map, only the pairs that satisfy the predicate.
Learn: Scala Functions: Quick and Easy Tutorial
ag. def size: Int
This returns the number of elements in the Map.
scala> m.size res94: Int = 3
ah. def sum: (A, B)
This returns the sum of all elements in the Map in Scala.
ai. def tail: Map[A, B]
This returns all elements except the first.
scala> m.tail res97: scala.collection.immutable.Map[String,Int] = Map(Megha -> 1, Ruchi -> 2)
aj. def take(n: Int): Map[A, B]
This returns the first n elements from the Map in Scala.
scala> m.take(2) res98: scala.collection.immutable.Map[String,Int] = Map(Ayushi -> 0, Megha -> 1)
ak. def takeRight(n: Int): Map[A, B]
This returns the last n elements.
scala> m.takeRight(2) res99: scala.collection.immutable.Map[String,Int] = Map(Megha -> 1, Ruchi -> 2)
al. def takeWhile(p: ((A, B)) => Boolean): Map[A, B]
This returns elements from the Map as long as the predicate is satisfied.
am. def toArray: Array[(A, B)]
This returns an Array from the Map.
scala> m.toArray res100: Array[(String, Int)] = Array((Ayushi,0), (Megha,1), (Ruchi,2))
an. def toList: List[A]
This returns a List from the Map.
scala> m.toList res101: List[(String, Int)] = List((Ayushi,0), (Megha,1), (Ruchi,2))
ao. def toSeq: Seq[A]
This returns a Sequence from the Scala Map.
scala> m.toSeq res102: Seq[(String, Int)] = Vector((Ayushi,0), (Megha,1), (Ruchi,2))
ap. def toSet: Set[A]
This returns a Set from the Map.
scala> m.toSet res103: scala.collection.immutable.Set[(String, Int)] = Set((Ayushi,0), (Megha,1), (Ruchi,2))
aq. def toString(): String
This returns a String from the Map.
scala> m.toString res104: String = Map(Ayushi -> 0, Megha -> 1, Ruchi -> 2)
So, this was all on Scala Map. Hope you like our explanation,
9. Conclusion
A Map in Scala is a collection holding key-value pairs. In this tutorial, we saw how to create, process, and call methods on them.