English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Map (mapping) is a iterable key-value pair (key/value structure.
All values can be retrieved through keys.
All keys in the Map are unique.
Map is also known as a hash table (Hash tables).
There are two types of Map, mutable and immutable, the difference being that mutable objects can be modified while immutable objects cannot.
By default, Scala uses an immutable Map. If you need to use a mutable collection, you need to explicitly import import scala.collection.mutable.Map Class
In Scala, you can use both mutable and immutable Maps. You can use Map directly for immutable Maps, and mutable.Map for mutable Maps. The following example demonstrates the application of immutable Maps:
// Empty hash table, key is a string, value is an integer 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 type of key-value pair. If you need to add a key-value pair, you can use + number, as shown below:
A += ('I' -> 1colors = colors A += ('J' -> 5colors = colors A += ('K' -> 10colors = colors A += ('L' -> 100)
Scala Map has three basic operations:
Method | Description |
---|---|
keys | Returns all keys (key) of the Map |
values | Returns all values (value) of the Map |
isEmpty | Returns true when the Map is empty |
The following examples demonstrate the basic applications of the above three methods:
Example object Test { val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F) val nums: Map[Int, Int] = Map() println("The keys in colors: ") + colors.keys) println("The values in colors: ") + colors.values) println("Check if colors is empty: ") + colors.isEmpty()) println("Check if nums is empty: ") + nums.isEmpty()) } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test The keys in colors: Set(red, azure, peru) The values in colors: MapLike(#FF0000, #F0FFFF, #CD853F) Check if colors is empty: false Check if nums is empty: true
to check if a specified Key exists in the Map ++ operator or 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 { val colors1 = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F) val colors2 val colors -= Map("blue"33> "#00 FF", -"yellow" > "#FFFF00", -"red" // ++ > "#FF0000" as an operator1 ++ : Map(blue2 )1 ++ : Map(blue2 var colors = colors + ) : "" // ++ : "" as a method1colors++.2colors = colors )1colors++.2println("colors" + ) : "" } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test : Map(blue1 ++ : Map(blue2 colors ) -)) : Map(blue33> #00 -FF, azure -> #F0FFFF, peru853> #CD -F, yellow -> #FFFF00, red : Map(blue1colors++.2(colors -)) : Map(blue33> #00 -FF, azure -> #F0FFFF, peru853> #CD -F, yellow -> #FFFF00, red
Output the keys and values of the Map
Example object Test { def main(args: Array[String]) {3val sites = Map("w" -"taobao"//www.w3"codebox" "codebox.com", -"taobao"//"baidu" "www.baidu.com", -"taobao"//"> "http:" The following uses foreach loop to output the keys and values of the Map: sites.keys.foreach{i => + print("Key = ", i ) + println(" Value = ", } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test sites(i)3Key = w//www.oldtoolbag.com codebox Value = http://www.baidu.com Key = baidu Value = http://Key = taobao Value = http:
to check if a specified Key exists in the Map You can use Map.contains
Example object Test { def main(args: Array[String]) {3val sites = Map("w" -"taobao"//www.w3"codebox" "codebox.com", -"taobao"//"baidu" "www.baidu.com", -"taobao"//"> "http:" println("www.taobao.com")3if(sites.contains("baidu")){ println("w")3if(sites.contains("w")){ + println("codebox key exists, the corresponding value is ":")3sites("w") } println("w")3println("codebox key does not exist") } if(sites.contains("baidu")){ println("baidu key exists, the corresponding value is ":") + sites("baidu") } println("baidu key does not exist") } if( sites.contains( "google" )){ println("google key exists, the corresponding value is ": + sites("google")) } println("google key does not exist") } } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test w3codebox key exists, the corresponding value is :http://www.oldtoolbag.com baidu key exists, the corresponding value is :http://www.baidu.com google key does not exist
The following table lists the commonly used methods of Scala Map:
Serial Number | Method and Description |
---|---|
1 | def ++(xs: Map[(A, B)]): Map[A, B] Return a new Map, composed of the new Map xs |
2 | def -(elem1: A, elem2: A, elems: A*): Map[A, B] Return a new Map, removing the key of elem1, elem2 or other elems. |
3 | def --(xs: GTO[A]): Map[A, B] Return a new Map, removing the corresponding key in xs object |
4 | def get(key: A): Option[B] Return the value of the specified key |
5 | def iterator: Iterator[(A, B)] Create a new iterator and output the key/value pair |
6 | def addString(b: StringBuilder): StringBuilder Attach all elements of the Map to a StringBuilder, and you can add a separator |
7 | def addString(b: StringBuilder, sep: String): StringBuilder Attach all elements of the Map to a StringBuilder, and you can add a separator |
8 | def apply(key: A): B Return the value of the specified key, or return the Map's default method if it does not exist |
9 | def clear(): Unit Clear the Map |
10 | def clone(): Map[A, B] Copy from one Map to another |
11 | def contains(key: A): Boolean If the Map contains the specified key, return true; otherwise, return false. |
12 | def copyToArray(xs: Array[(A, B)]): Unit Copies the collection to an array |
13 | def count(p: ((A, B)) => Boolean): Int Calculates the number of elements in the collection that meet the specified conditions |
14 | def default(key: A): B Defines the default value of the Map, returning it when the key does not exist. |
15 | def drop(n: Int): Map[A, B] Returns a new collection by discarding the first n elements |
16 | def dropRight(n: Int): Map[A, B] Returns a new collection by discarding the last n elements |
17 | def dropWhile(p: ((A, B)) => Boolean): Map[A, B] Discards elements from left to right until condition p does not hold |
18 | def empty: Map[A, B] Returns an empty Map of the same type |
19 | def equals(that: Any): Boolean If two Maps are equal (key/Returns true if all values are equal, otherwise returns false |
20 | def exists(p: ((A, B)) => Boolean): Boolean Determines whether the element meeting the specified condition exists in the collection |
21 | def filter(p: ((A, B))=> Boolean): Map[A, B] Returns all collections that meet the specified conditions |
22 | def filterKeys(p: (A) => Boolean): Map[A, B] Returns an immutable Map that meets the specified conditions |
23 | def find(p: ((A, B)) => Boolean): Option[(A, B)] Finds the first element in the collection that satisfies 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/p> |
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 strings |
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 it meets the specified conditions |
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 element |
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 satisfy the specified condition |
41 | def toArray: Array[(A, B)] Convert collection to 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 object |
More methods can be referred to API Documentation