映射Map
- Map可以称之为映射。它是由键值对组成的集合。scala当中的Map集合与java当中的Map类似,也是key,value对形式的。
- 在scala中,Map也分为不可变Map和可变 Map。
1 不可变Map
- 定义语法
val/var map = Map(键->值, 键->值, 键->值...) // 推荐,可读性更好
val/var map = Map((键, 值), (键, 值), (键, 值), (键, 值)...)
- 示例
scala> val map1 = Map("zhangsan"->30, "lisi"->40)
map: scala.collection.immutable.Map[String,Int] = Map(zhangsan -> 30, lisi -> 40)
scala> val map2 = Map(("zhangsan", 30), ("lisi", 30))
map: scala.collection.immutable.Map[String,Int] = Map(zhangsan -> 30, lisi -> 30)
// 根据key获取value
scala> map1("zhangsan")
res10: Int = 30
2 可变Map
-
可变Map需要手动导入import scala.collection.mutable.Map, 定义语法与不可变Map一致。
-
示例
//导包
scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map
//定义可变的map
scala> val map3 = Map("zhangsan"->30, "lisi"->40)
map3: scala.collection.mutable.Map[String,Int] = Map(lisi -> 40, zhangsan -> 30)
//获取zhangsan这个key对应的value
scala> map3("zhangsan")
res26: Int = 30
//给zhangsan这个key重新赋值value
scala> map3("zhangsan")=50
//显示map3
scala> map3
res28: scala.collection.mutable.Map[String,Int] = Map(lisi -> 40, zhangsan -> 50)
3 Map基本操作
- 创建一个可变的map
//导包
scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map
scala> val map = Map("zhangsan"->30, "lisi"->40)
map: scala.collection.mutable.Map[String,Int] = Map(lisi -> 40, zhangsan -> 30)
- 按照key获取value
// 获取zhagnsan的年龄
scala> map("zhangsan")
res10: Int = 30
// 获取wangwu的年龄,如果wangwu不存在,则返回-1 比较友好,避免遇到不存在的key而报错
scala> map.getOrElse("wangwu", -1)
res11: Int = -1
- 修改key对应的value
scala> map("lisi")=50
- 添加key-value键值对
scala> map+=("wangwu" ->35)
res12: map.type = Map(lisi -> 50, zhangsan -> 30, wangwu -> 35)
- 删除key-value键值对
scala> map -="wangwu"
res13: map.type = Map(lisi -> 50, zhangsan -> 30)
- 获取所有的key和所有的value
//获取所有的key
scala> map.keys
res36: Iterable[String] = Set(lisi, zhangsan)
//获取所有的key
scala> map.keySet
res37: scala.collection.Set[String] = Set(lisi, zhangsan)
//获取所有的value
scala> map.values
res38: Iterable[Int] = HashMap(50, 30)
- 遍历map
//第一种遍历
scala> for(k <- map.keys) println(k+" -> " +map(k))
lisi -> 50
zhangsan -> 30
//第二种遍历
scala> for((k,v) <- map) println(k+" -> "+v)
lisi -> 50
zhangsan -> 30