scala集合三大类(seq序列,set集,map映射)——map映射
scala集合三大类(seq序列,set集,map映射)——map映射
map映射:
scala> import scala.collection.mutable.HashMap._
import scala.collection.mutable.HashMap._
scala> val map1 = new HashMap[String,Int]()
map1: scala.collection.mutable.HashMap[String,Int] = HashMap()
scala> map1("scala") = 1
scala> map1
res83: scala.collection.mutable.HashMap[String,Int] = HashMap(scala -> 1)
scala> map1 += (("java",2)) //使用+=添加一个元素
res84: map1.type = HashMap(java -> 2, scala -> 1)
scala> map1
res85: scala.collection.mutable.HashMap[String,Int] = HashMap(java -> 2, scala -> 1)
scala> map1 += (("python",3),("web",4)) //添加多个元素
^
warning: method += in trait Growable is deprecated (since 2.13.0): Use `++=` (addAll) instead of varargs `+=`
res86: map1.type = HashMap(python -> 3, java -> 2, web -> 4, scala -> 1)
scala> map1
res88: scala.collection.mutable.HashMap[String,Int] = HashMap(python -> 3, java -> 2, web -> 4, scala -> 1)
scala> map1 -= ("web") //使用 -= 移除map里面的一个元素
res89: map1.type = HashMap(python -> 3, java -> 2, scala -> 1)
scala> map1.remove("java") //移除一个元素
res90: Option[Int] = Some(2)
scala> map1.put("c++",6) //添加一个元素 put 操作方法实现
res92: Option[Int] = None
scala> map1
res93: scala.collection.mutable.HashMap[String,Int] = HashMap(python -> 3, c++ -> 6, scala -> 1)