Basic Operations On MAP: Example

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

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.

The Following is the example statements to declare immutable Maps −

// Empty hash table whose keys are strings and values are integers:
var A:Map[Char,Int] = Map()

// A map with keys and values.


val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

While defining empty map, the type annotation is necessary as the system needs to assign a
concrete type to variable. If we want to add a key-value pair to a Map, we can use the operator +
as follows.

A + = ('I' -> 1)
A + = ('J' -> 5)
A + = ('K' -> 10)
A + = ('L' -> 100)

Basic Operations on MAP


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

Sr.No Methods & Description


keys
1
This method returns an iterable containing each key in the map.
values
2
This method returns an iterable containing each value in the map.
isEmpty
3
This 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" -> "#FF0000", "azure" -> "#F0FFFF", "peru" ->
"#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" -> "#FF0000", "azure" -> "#F0FFFF", "peru" ->
"#CD853F")
val colors2 = Map("blue" -> "#0033FF", "yellow" -> "#FFFF00", "red" ->
"#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" -> "#FF0000", "azure" -> "#F0FFFF","peru" ->
"#CD853F")

colors.keys.foreach{ i =>
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
Key = red Value = #FF0000
Key = azure Value = #F0FFFF
Key = peru Value = #CD853F

Check for a key in Map


You can use either Map.contains method to test if a given key exists in the map or not. Try the
Following example program to key checking.

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

if( colors.contains( "red" )) {


println("Red key exists with value :" + colors("red"))
} else {
println("Red key does not exist")
}

if( colors.contains( "maroon" )) {


println("Maroon key exists with value :" + colors("maroon"))
} else {
println("Maroon key does not exist")
}
}
}

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.No Methods with Description


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

Scala has a rich set of collection library. Collections are containers of things. Those containers
can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may
have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).

Collections may be strict or lazy. Lazy collections have elements that may not consume memory
until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of
the reference can change) or immutable (the thing that a reference refers to is never changed).
Note that immutable collections may contain mutable items.

For some problems, mutable collections work better, and for others, immutable collections work
better. When in doubt, it is better to start with an immutable collection and change it later if you
need mutable ones.

This chapter throws light on the most commonly used collection types and most frequently used
operations over those collections.

Sr.No Collections with Description


Scala Lists
1
Scala's List[T] is a linked list of type T.
Scala Sets
2
A set is a collection of pairwise different elements of the same type.
3 Scala Maps
A Map is a collection of key/value pairs. Any value can be retrieved based on its key.
Scala Tuples
4
Unlike an array or list, a tuple can hold objects with different types.
Scala Options
5
Option[T] provides a container for zero or one element of a given type.
Scala Iterators
6
An iterator is not a collection, but rather a way to access the elements of a collection
one by one.

You might also like