Map(映射)是一種可迭代的鍵值對(duì)(key/value)結(jié)構(gòu)。
所有的值都可以通過(guò)鍵來(lái)獲取。
Map 中的鍵都是唯一的。
Map 也叫哈希表(Hash tables)。
Map 有兩種類型,可變與不可變,區(qū)別在于可變對(duì)象可以修改它,而不可變對(duì)象不可以。
默認(rèn)情況下 Scala 使用不可變 Map。如果你需要使用可變集合,你需要顯式的引入 import scala.collection.mutable.Map 類
在 Scala 中 你可以同時(shí)使用可變與不可變 Map,不可變的直接使用 Map,可變的使用 mutable.Map。以下示例演示了不可變 Map 的應(yīng)用:
// 空哈希表,鍵為字符串,值為整型
var A:Map[Char,Int] = Map()
// Map 鍵值對(duì)演示
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")定義 Map 時(shí),需要為鍵值對(duì)定義類型。如果需要添加 key-value 對(duì),可以使用 + 號(hào),如下所示:
A += ('I' -> 1)
A += ('J' -> 5)
A += ('K' -> 10)
A += ('L' -> 100)Scala Map 有三個(gè)基本操作:
| 方法 | 描述 |
|---|---|
| keys | 返回 Map 所有的鍵(key) |
| values | 返回 Map 所有的值(value) |
| isEmpty | 在 Map 為空時(shí)返回true |
以下示例演示了以上三個(gè)方法的基本應(yīng)用:
object Test {
def main(args: Array[String]) {
val colors = Map("red" -> "#FF0000",
"azure" -> "#F0FFFF",
"peru" -> "#CD853F")
val nums: Map[Int, Int] = Map()
println( "colors 中的鍵為 : " + colors.keys )
println( "colors 中的值為 : " + colors.values )
println( "檢測(cè) colors 是否為空 : " + colors.isEmpty )
println( "檢測(cè) nums 是否為空 : " + nums.isEmpty )
}
}執(zhí)行以上代碼,輸出結(jié)果為:
$ scalac Test.scala $ scala Test colors 中的鍵為 : Set(red, azure, peru) colors 中的值為 : MapLike(#FF0000, #F0FFFF, #CD853F) 檢測(cè) colors 是否為空 : false 檢測(cè) nums 是否為空 : true
你可以使用 ++ 運(yùn)算符或 Map.++() 方法來(lái)連接兩個(gè) Map,Map 合并時(shí)會(huì)移除重復(fù)的 key。以下演示了兩個(gè) Map 合并的示例:
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")
// ++ 作為運(yùn)算符
var colors = colors1 ++ colors2
println( "colors1 ++ colors2 : " + colors )
// ++ 作為方法
colors = colors1.++(colors2)
println( "colors1.++(colors2) : " + colors )
}
}執(zhí)行以上代碼,輸出結(jié)果為:
$ 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)
以下通過(guò) foreach 循環(huán)輸出 Map 中的 keys 和 values:
object Test {
def main(args: Array[String]) {
val sites = Map("nhooo" -> "",
"baidu" -> "http://www.baidu.com",
"taobao" -> "http://www.taobao.com")
sites.keys.foreach{ i =>
print( "Key = " + i )
println(" Value = " + sites(i) )}
}
}執(zhí)行以上代碼,輸出結(jié)果為:
$ scalac Test.scala $ scala Test Key = nhooo Value = Key = baidu Value = http://www.baidu.com Key = taobao Value = http://www.taobao.com
你可以使用 Map.contains 方法來(lái)查看 Map 中是否存在指定的 Key。示例如下:
object Test {
def main(args: Array[String]) {
val sites = Map("nhooo" -> "",
"baidu" -> "http://www.baidu.com",
"taobao" -> "http://www.taobao.com")
if( sites.contains( "nhooo" )){
println("nhooo 鍵存在,對(duì)應(yīng)的值為 :" + sites("nhooo"))
}else{
println("nhooo 鍵不存在")
}
if( sites.contains( "baidu" )){
println("baidu 鍵存在,對(duì)應(yīng)的值為 :" + sites("baidu"))
}else{
println("baidu 鍵不存在")
}
if( sites.contains( "google" )){
println("google 鍵存在,對(duì)應(yīng)的值為 :" + sites("google"))
}else{
println("google 鍵不存在")
}
}
}執(zhí)行以上代碼,輸出結(jié)果為:
$ scalac Test.scala $ scala Test nhooo 鍵存在,對(duì)應(yīng)的值為 : baidu 鍵存在,對(duì)應(yīng)的值為 :http://www.baidu.com google 鍵不存在
下表列出了 Scala Map 常用的方法:
| 序號(hào) | 方法及描述 |
|---|---|
| 1 | def ++(xs: Map[(A, B)]): Map[A, B] 返回一個(gè)新的 Map,新的 Map xs 組成 |
| 2 | def -(elem1: A, elem2: A, elems: A*): Map[A, B] 返回一個(gè)新的 Map, 移除 key 為 elem1, elem2 或其他 elems。 |
| 3 | def --(xs: GTO[A]): Map[A, B] 返回一個(gè)新的 Map, 移除 xs 對(duì)象中對(duì)應(yīng)的 key |
| 4 | def get(key: A): Option[B] 返回指定 key 的值 |
| 5 | def iterator: Iterator[(A, B)] 創(chuàng)建新的迭代器,并輸出 key/value 對(duì) |
| 6 | def addString(b: StringBuilder): StringBuilder 將 Map 中的所有元素附加到StringBuilder,可加入分隔符 |
| 7 | def addString(b: StringBuilder, sep: String): StringBuilder 將 Map 中的所有元素附加到StringBuilder,可加入分隔符 |
| 8 | def apply(key: A): B 返回指定鍵的值,如果不存在返回 Map 的默認(rèn)方法 |
| 9 | def clear(): Unit 清空 Map |
| 10 | def clone(): Map[A, B] 從一個(gè) Map 復(fù)制到另一個(gè) Map |
| 11 | def contains(key: A): Boolean 如果 Map 中存在指定 key,返回 true,否則返回 false。 |
| 12 | def copyToArray(xs: Array[(A, B)]): Unit 復(fù)制集合到數(shù)組 |
| 13 | def count(p: ((A, B)) => Boolean): Int 計(jì)算滿足指定條件的集合元素?cái)?shù)量 |
| 14 | def default(key: A): B 定義 Map 的默認(rèn)值,在 key 不存在時(shí)返回。 |
| 15 | def drop(n: Int): Map[A, B] 返回丟棄前n個(gè)元素新集合 |
| 16 | def dropRight(n: Int): Map[A, B] 返回丟棄最后n個(gè)元素新集合 |
| 17 | def dropWhile(p: ((A, B)) => Boolean): Map[A, B] 從左向右丟棄元素,直到條件p不成立 |
| 18 | def empty: Map[A, B] 返回相同類型的空 Map |
| 19 | def equals(that: Any): Boolean 如果兩個(gè) Map 相等(key/value 均相等),返回true,否則返回false |
| 20 | def exists(p: ((A, B)) => Boolean): Boolean 判斷集合中指定條件的元素是否存在 |
| 21 | def filter(p: ((A, B))=> Boolean): Map[A, B] 返回滿足指定條件的所有集合 |
| 22 | def filterKeys(p: (A) => Boolean): Map[A, B] 返回符合指定條件的不可變 Map |
| 23 | def find(p: ((A, B)) => Boolean): Option[(A, B)] 查找集合中滿足指定條件的第一個(gè)元素 |
| 24 | def foreach(f: ((A, B)) => Unit): Unit 將函數(shù)應(yīng)用到集合的所有元素 |
| 25 | def init: Map[A, B] 返回所有元素,除了最后一個(gè) |
| 26 | def isEmpty: Boolean 檢測(cè) Map 是否為空 |
| 27 | def keys: Iterable[A] 返回所有的key/p> |
| 28 | def last: (A, B) 返回最后一個(gè)元素 |
| 29 | def max: (A, B) 查找最大元素 |
| 30 | def min: (A, B) 查找最小元素 |
| 31 | def mkString: String 集合所有元素作為字符串顯示 |
| 32 | def product: (A, B) 返回集合中數(shù)字元素的積。 |
| 33 | def remove(key: A): Option[B] 移除指定 key |
| 34 | def retain(p: (A, B) => Boolean): Map.this.type 如果符合滿足條件的返回 true |
| 35 | def size: Int 返回 Map 元素的個(gè)數(shù) |
| 36 | def sum: (A, B) 返回集合中所有數(shù)字元素之和 |
| 37 | def tail: Map[A, B] 返回一個(gè)集合中除了第一元素之外的其他元素 |
| 38 | def take(n: Int): Map[A, B] 返回前 n 個(gè)元素 |
| 39 | def takeRight(n: Int): Map[A, B] 返回后 n 個(gè)元素 |
| 40 | def takeWhile(p: ((A, B)) => Boolean): Map[A, B] 返回滿足指定條件的元素 |
| 41 | def toArray: Array[(A, B)] 集合轉(zhuǎn)數(shù)組 |
| 42 | def toBuffer[B >: A]: Buffer[B] 返回緩沖區(qū),包含了 Map 的所有元素 |
| 43 | def toList: List[A] 返回 List,包含了 Map 的所有元素 |
| 44 | def toSeq: Seq[A] 返回 Seq,包含了 Map 的所有元素 |
| 45 | def toSet: Set[A] 返回 Set,包含了 Map 的所有元素 |
| 46 | def toString(): String 返回字符串對(duì)象 |
更多方法可以參考 API文檔