1、Map、HashMap都分为immutable(不可变)和mutable(可变)两种类型。
2、创建一个不可变Map
//创建一个不可变Map
val map = Map("name"->"LiSi","Sex"->"man")
println(map.get("name")) //Some(LiSi)
println(map("name")) //LiSi
// map +=("address"->"BeiJing") 报错
//不可变的映射,但可以做一些有用的操作获取一个新的映射:
val newScores = map +("address"->"zhengzhou","hobby"->"唱歌")
println(newScores.mkString(",")) //name -> LiSi,Sex -> man,address -> zhengzhou,hobby -> 唱歌
3、创建一个可变Map
val map01 = mutable.Map("name"->"LiSi","Sex"->"man")
map01 +=("address"->"BeiJing")
map01("Sex")="women"
println(map01.mkString(",")) //address -> BeiJing,name -> LiSi,Sex -> women
//创建一个空映射,必须new它的实现类,并且给出泛型的类型
val map02 = mutable.Map()
// map02 +=("address"->"BeiJing") 报错,空映射不能加
val map03 = new mutable.HashMap[String,Any]()
map03 +=("address"->"BeiJing")
println(map03.mkString(","))//address -> BeiJing
4、在可变Map中添加修改Map
//在可变Map中添加修改Map
val map04 = new mutable.HashMap[String,Any]()
map04+=("name"->"xiaoming","age"->"15")
map04("address")="北京"
map04("name")="zhangsan"
map04.update("age",19)
println(map04.mkString(","))//address -> 北京,age -> 19,name -> zhangsan
//删除可变Map中的映射关系
map04-="address"
println(map04.mkString(","))//age -> 19,name -> zhangsan
//判断Map中是否存在某键
//如果存在adress键,便返回该键的值,否则返回"Map中不存在该键!"
val address = map04.getOrElse("address","Map中不存在该键!")
println(address)//Map中不存在该键!
5、遍历Map
//遍历Map
for(key<-map04.keys){
println("key:"+key+" value:"+map04(key))
}
for(key<-map04.keys){
val value=map04.get(key)
value match {
case Some(v)=>println("key:"+key+" value:"+v)
}
}
6、注意:
当使用map(key)获得值时,如果key不存在的情况下会报错;所以使用map.get(key)比较安全
def main(args: Array[String]): Unit = {
val map = Map("aa"->"AA","bb"->"BB")
println(map("aa")) //AA
println(map.get("cc")) //None
println(map("cc")) //报异常:java.util.NoSuchElementException: key not found: cc
}