创建map
scala> val map = Map("name"->"erhuan","age"->20)
map: scala.collection.immutable.Map[String,Any] = Map(name -> erhuan, age -> 20)
//等效于
scala> val map = Map(("name","erhuan"),("age"->20))
map: scala.collection.immutable.Map[String,Any] = Map(name -> erhuan, age -> 20)
创建可变map
scala> val map = scala.collection.mutable.Map("name"->"erhuan","age"->20)
map: scala.collection.mutable.Map[String,Any] = Map(age -> 20, name -> erhuan)
获取map中的值
scala> val name=map("name")
name: Any = erhuan
//查看map是否包含某个key
scala> if(map.contains("name")) map("name")
res0: Any = erhuan
更新map
//更新值
scala> map("name")="lilin"
scala> map
res2: scala.collection.mutable.Map[String,Any] = Map(age -> 20, name -> lilin)
//添加键值对
scala> map+=("tall"->1.5)
res4: map.type = Map(tall -> 1.5, age -> 20, name -> lilin)
//删除键值对
scala> map-=("tall")
res5: map.type = Map(age -> 20, name -> lilin)
其他操作
// 遍历所有
scala> for((k,v)<-map){println(k+"="+name)}
age=erhuan
name=erhuan
//便利key
scala> map.keySet
res10: scala.collection.Set[String] = Set(age, name)
//遍历values
scala> for(v <-map.values) println(v)
20
lilin
// k v反转
scala> for((k,v)<-map) yield(v,k)
res12: scala.collection.mutable.Map[Any,String] = Map(20 -> age, lilin -> name)