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> university res9: 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 0 bh: Any = Xiamen University scala> print(bh) Xiamen University
b、不变映射
不可变映射不能更新键值、不能增加键值。想要更新、增加就需要创建可变映射
scala> import scala.collection.mutable.Map import scala.collection.mutable.Map scala> 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 ,value scala> for ((k,v) <-university2) printf("Code is : %s and name is: %s\n",k,v) Code is : XMU and name is: Ximan University Code is : SDU and name is: Shandong University Code is : WHU and name is: Wuhan University Code is : THU and name is: Tsinghua University Code is : FZU and name is: Fuzhou University Code is : TJU and name is: Tianjin University Code is : PKU and name is: Peking University //只输出key scala> for (k<-university2.keys) println(k) XMU THU PKU //只输出value scala> for (v<-university2.values) println(v) Xiamen University Tsinghua University Peking University