YouTip LogoYouTip

Scala Maps

Scala Collections Scala Collections Map is an iterable key-value pair (key/value) structure. All values can be retrieved through their keys. Keys in a Map are unique. 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 a mutable collection, you need to explicitly import the **import scala.collection.mutable.Map** class In Scala, you can use both mutable and immutable Maps simultaneously. Use Map directly for immutable ones, and mutable.Map for mutable ones. The following example demonstrates the application of an immutable Map: // Empty hash table, keys are strings, values are integersvar 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 key-value pairs, you can use the + operator, as shown below: A += ('I' -> 1) A += ('J' -> 5) A += ('K' -> 10) A += ('L' -> 100) * * * ## Map Basic Operations 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 if the Map is empty | ### Example The following example demonstrates the basic application of the above three methods: ## Example object Test { def main(args: Array){ 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) } } Executing the above code, the output result is: $ scalac Test.scala $ scala Test Keys in colors : Set(red, azure, peru) Values in colors : MapLike(#FF0000, #F0FFFF, #CD853F)Check if colors is empty : falseCheck if nums is empty : true * * * ## Map Merging You can use the **++** operator or the **Map.++()** method to concatenate two Maps. Duplicate keys will be removed when Maps are merged. The following example demonstrates the merging of two Maps: ## Example object Test { def main(args: Array){ 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 ) } } Executing the above code, the output result is: $ 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) * * * ## Output Map Keys and Values The following outputs the keys and values in the Map through a foreach loop: ## Example object Test { def main(args: Array){ val sites = Map("tutorial" ->"", "baidu" ->"http://www.baidu.com", "taobao" ->"http://www.taobao.com") sites.keys.foreach{ i => print("Key = " + i ) println(" Value = " + sites(i))} } } Executing the above code, the output result is: $ scalac Test.scala $ scala TestKey = tutorial Value = = baidu Value = http://www.baidu.comKey = taobao Value = http://www.taobao.com * * * ## Check if a Specified Key Exists in the Map You can use the **Map.contains** method to check if a specified key exists in the Map. An example is as follows: ## Example object Test { def main(args: Array){ val sites = Map("tutorial" ->"", "baidu" ->"http://www.baidu.com", "taobao" ->"http://www.taobao.com") if( sites.contains("tutorial")){ println("tutorial key exists, corresponding value is :"+ sites("tutorial")) }else{ println("tutorial key does not exist") } if( sites.contains("baidu")){ println("baidu key exists, corresponding value is :"+ sites("baidu")) }else{ println("baidu key does not exist") } if( sites.contains("google")){ println("google key exists, corresponding value is :"+ sites("google")) }else{ println("google key does not exist") } } } Executing the above code, the output result is: $ scalac Test.scala $ scala Test tutorial key exists, corresponding value is : baidu key exists, corresponding value is :http://www.baidu.com google key does not exist * * * ## Scala Map Methods The following table lists the commonly used methods for Scala Map: | No. | Method & Description | | --- | --- | | 1 | **def ++(xs: Map[(A, B)]): Map[A, B]** Returns a new Map composed of this Map and xs | | 2 | **def -(elem1: A, elem2: A, elems: A*): Map[A, B]** Returns a new Map with the keys elem1, elem2, or other elems removed. | | 3 | **def --(xs: GTO): Map[A, B]** Returns a new Map with the keys corresponding to the xs object removed | | 4 | **def get(key: A): Option** Returns the value for the specified key | | 5 | **def iterator: Iterator[(A, B)]** Creates a new iterator and outputs the key/value pairs | | 6 | **def addString(b: StringBuilder): StringBuilder** Appends all elements of the Map to a StringBuilder, with a separator optionally added | | 7 | **def addString(b: StringBuilder, sep: String): StringBuilder** Appends all elements of the Map to a StringBuilder, with a separator | | 8 | **def apply(key: A): B** Returns the value for the specified key, or returns the Map's default method if it does not exist | | 9 | **def clear(): Unit** Clears the Map | | 10 | **def clone(): Map[A, B]** Copies from one Map to another Map | | 11 | **def contains(key: A): Boolean** Returns true if the specified key exists in the Map, otherwise returns false. | | 12 | **def copyToArray(xs: Array[(A, B)]): Unit** Copies the collection to an array | | 13 | **def count(p: ((A, B)) => Boolean): Int** Counts the number of collection elements that satisfy the specified condition | | 14 | **def default(key: A): B** Defines the default value of the Map, returned when the key does not exist. | | 15 | **def drop(n: Int): Map[A, B]** Returns a new collection discarding the first n elements | | 16 | **def dropRight(n: Int): Map[A, B]** Returns a new collection discarding the last n elements | | 17 | **def dropWhile(p: ((A, B)) => Boolean): Map[A, B]** Drops elements from left to right until condition p is not met | | 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 key/value are equal), otherwise returns false | | 20 | **def exists(p: ((A, B)) => Boolean): Boolean** Determines whether an element satisfying the specified condition exists in the collection | | 21 | **def filter(p: ((A, B))=> Boolean): Map[A, B]** Returns all collections that satisfy the specified condition | | 22 | **def filterKeys(p: (A) => Boolean): Map[A, B]** Returns an immutable Map that matches the specified condition | | 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 a function to all elements of the collection | | 25 | **def init: Map[A, B]** Returns all elements except the last
← Scala TuplesScala Sets β†’