Scala Map (Mapping)
A Map (mapping) is an iterable key/value structure.
All values can be retrieved through their keys.
The keys in a Map are unique.
A Map is also known as a hash table.
There are two types of Maps: mutable and immutable. The difference is that mutable objects can be modified, while immutable objects cannot.
By default, Scala uses immutable Maps. If you need to use mutable collections, you need to explicitly import the import scala.collection.mutable.Map class.
In Scala, you can use both mutable and immutable Maps. Immutable ones are used directly with Map, and mutable ones with mutable.Map. The following example demonstrates the use of an immutable Map:
// Empty hash table, keys are strings, values are integers
var A: Map[Char, Int] = Map()
// Map key-value pair demonstration
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")
When defining a Map, you need to define the types for the key-value pairs. If you need to add a key-value pair, you can use the + sign, as shown below:
A += ('I' -> 1)
A += ('J' -> 5)
A += ('K' -> 10)
A += ('L' -> 100)
Basic Operations of Map
Scala Map has three basic operations:
Method | Description |
---|---|
keys | Returns all the keys of the Map |
values | Returns all the values of the Map |
isEmpty | Returns true when the Map is empty |
Example
The following example demonstrates the basic application of the above three methods:
Example
object Test {
def main(args: Array[String]) {
val colors = Map("red" -> "#FF0000",
"azure" -> "#F0FFFF",
"peru" -> "#CD853F")
val nums: Map[Int, Int] = Map()
println("colors keys: " + colors.keys)
println("colors values: " + colors.values)
println("Check if colors is empty: " + colors.isEmpty)
println("Check if nums is empty: " + nums.isEmpty)
}
}
Running the above code, the output will be:
$ scalac Test.scala
$ scala Test
colors keys: Set(red, azure, peru)
colors values: MapLike(#FF0000, #F0FFFF, #CD853F)
Check if colors is empty: false
Check if nums is empty: true
Map Merging
You can use the ++ operator or the Map.++() method to connect two Maps. When merging Maps, duplicate keys will be removed. The following demonstrates an example of merging two Maps:
Example
object Test {
def main(args: Array[String]) {
val colors1 = Map("red" -> "#FF0000",
"azure" -> "#F0FFFF",
"peru" -> "#CD853F")
val colors2 = Map("blue" -> "#0033FF",
"yellow" -> "#FFFF00",
"red" -> "#FF0000")
// ++ as an operator
var colors = colors1 ++ colors2
println("colors1 ++ colors2: " + colors)
// ++ as a method
colors = colors1.++(colors2)
println("colors1.++(colors2): " + colors)
}
}
Running the above code, the output will be:
$ scalac Test.scala
$ scala Test
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)
Outputting Map Keys and Values
The following uses a foreach loop to output the keys and values in a Map:
Example
object Test {
def main(args: Array[String]) {
val sites = Map("tutorialpro" -> "http://www.tutorialpro.org",
"baidu" -> "http://www.baidu.com",
"taobao" -> "http://www.taobao.com")
sites.keys.foreach { i =>
print("Key = " + i)
println(" Value = " + sites(i))
}
}
}
| 18 | def empty: Map[A, B] Returns an empty Map of the same type | | 19 | def equals(that: Any): Boolean Returns true if two Maps are equal (both keys and values are equal), otherwise returns false | | 20 | def exists(p: ((A, B)) => Boolean): Boolean Checks if there is an element in the collection that meets the specified condition | | 21 | def filter(p: ((A, B))=> Boolean): Map[A, B] Returns all elements in the collection that meet the specified condition | | 22 | def filterKeys(p: (A) => Boolean): Map[A, B] Returns an immutable Map with keys that meet the specified condition | | 23 | def find(p: ((A, B)) => Boolean): Option[(A, B)] Finds the first element in the collection that meets the specified condition | | 24 | def foreach(f: ((A, B)) => Unit): Unit Applies the function to all elements of the collection | | 25 | def init: Map[A, B] Returns all elements except the last one | | 26 | def isEmpty: Boolean Checks if the Map is empty | | 27 | def keys: Iterable[A] Returns all keys | | 28 | def last: (A, B) Returns the last element | | 29 | def max: (A, B) Finds the maximum element | | 30 | def min: (A, B) Finds the minimum element | | 31 | def mkString: String Displays all elements of the collection as a string | | 32 | def product: (A, B) Returns the product of the numeric elements in the collection | | 33 | def remove(key: A): Option[B] Removes the specified key | | 34 | def retain(p: (A, B) => Boolean): Map.this.type Returns true if the condition is met | | 35 | def size: Int Returns the number of elements in the Map | | 36 | def sum: (A, B) Returns the sum of all numeric elements in the collection | | 37 | def tail: Map[A, B] Returns all elements of a collection except the first one | | 38 | def take(n: Int): Map[A, B] Returns the first n elements | | 39 | def takeRight(n: Int): Map[A, B] Returns the last n elements | | 40 | def takeWhile(p: ((A, B)) => Boolean): Map[A, B] Returns elements that meet the specified condition | | 41 | def toArray: Array[(A, B)] Converts the collection to an array | | 42 | def toBuffer[B >: A]: Buffer[B] Returns a buffer containing all elements of the Map | | 43 | def toList: List[A] Returns a List containing all elements of the Map | | 44 | def toSeq: Seq[A] Returns a Seq containing all elements of the Map | | 45 | def toSet: Set[A] Returns a Set containing all elements of the Map | | 46 | def toString(): String Returns a string representation of the object |
More methods can be referred to in the API documentation