1、定义
在Scala中,映射(map)是一系列键值对的集合。也就是说建立了键和值的对应关系。在映射中,所有的值都可以通过键来找到。
映射包括两种,不可变和可变两种,默认创建的都是不可变映射,如果要创建可变映射,需要导入scala.collection.mutable.Map包。
2、创建映射
a、不可变映射
scala> val university = Map("XMU" -> "Xiamen University", "THU" -> "Tsinghua University","PKU"->"Peking University")university: scala.collection.immutable.Map[String,String] = Map(XMU -> Xiamen University, THU -> Tsinghua University, PKU -> Peking University)scala> universityres9: scala.collection.immutable.Map[String,String] = Map(XMU -> Xiamen University, THU -> Tsinghua University, PKU -> Peking University)scala> print(university)Map(XMU -> Xiamen University, THU -> Tsinghua University, PKU -> Peking University)//获取某个值,可以通过对应的键来获取scala> print(university("XMU"))Xiamen University//判断映射中是否包含某个值scala> val bh = if(university.contains("XMU")) university("XMU") else 0bh: Any = Xiamen Universityscala> print(bh)Xiamen University
b、不变映射
不可变映射不能更新键值、不能增加键值。想要更新、增加就需要创建可变映射
scala> import scala.collection.mutable.Mapimport scala.collection.mutable.Mapscala> val university2 = Map("XMU" -> "Xiamen University", "THU" -> "Tsinghua University","PKU"->"Peking University")university2: scala.collection.mutable.Map[String,String] = Map(XMU -> Xiamen University, THU -> Tsinghua University, PKU -> Peking University)scala> //更新已有元素的值scala> university2("XMU") = "Ximan University"scala> //添加新元素scala> university2("FZU") = "Fuzhou University"scala> //也可以使用+=操作来添加新的元素,如下:scala> university2 += ("TJU"->"Tianjin University") res11: university2.type = Map(XMU -> Ximan University, THU -> Tsinghua University, FZU -> Fuzhou University, TJU -> Tianjin University, PKU -> Peking University)scala> university2 += ("SDU"->"Shandong University","WHU"->"Wuhan University")res12: university2.type = Map(XMU -> Ximan University, SDU -> Shandong University, WHU -> Wuhan University, THU -> Tsinghua University, FZU -> Fuzhou University, TJU -> Tianjin University, PKU -> Peking University)scala> print(university2)Map(XMU -> Ximan University, SDU -> Shandong University, WHU -> Wuhan University, THU -> Tsinghua University, FZU -> Fuzhou University, TJU -> Tianjin University, PKU -> Peking University)
3、遍历输出
//输出key ,valuescala> for ((k,v) <-university2) printf("Code is : %s and name is: %s\n",k,v)Code is : XMU and name is: Ximan UniversityCode is : SDU and name is: Shandong UniversityCode is : WHU and name is: Wuhan UniversityCode is : THU and name is: Tsinghua UniversityCode is : FZU and name is: Fuzhou UniversityCode is : TJU and name is: Tianjin UniversityCode is : PKU and name is: Peking University//只输出keyscala> for (k<-university2.keys) println(k)XMUTHUPKU//只输出valuescala> for (v<-university2.values) println(v)Xiamen UniversityTsinghua UniversityPeking University