scala的map映射
scala的map映射:
scala> val map1 = Map("scala"->1, "java"->2,"python"->3) //定义map方法一,都是调用其静态方法
map1: scala.collection.immutable.Map[String,Int] = Map(scala -> 1, java -> 2, python -> 3)
scala> val map2 = Map(("scala",1),("java",2),("python",3)) //定义map方法二,都是调用其静态方法
map2: scala.collection.immutable.Map[String,Int] = Map(scala -> 1, java -> 2, python -> 3)
scala> map1("scala") //取键为scala对应的内容
res39: Int = 1
scala> map1("scala") = 5 //默认是不可变的,需要导入包才可改map里面对key值对应的内容
^
error: value update is not a member of scala.collection.immutable.Map[String,Int]
did you mean updated?
scala> import scala.collection.mutable._
import scala.collection.mutable._
scala> val map1 = Map("scala"->1, "java"->2,"python"->3) //导包后要重新定义,因为是没导包前定义的,默认为不可变的,所以需要在导包后定义的才是变长map
map1: scala.collection.mutable.Map[String,Int] = HashMap(python -> 3, java -> 2, scala -> 1)
scala> map1("scala") = 5 //更改键是scala的对应内容 ,val 修饰的是变量引用不可变,现在这个修改的是变量引用对应的内容。
scala> map1("scala")
res43: Int = 5
scala> map1.getOrElse("C#",-1) //取键为“c#", 如若映射里面没有此键时会报错,常使用方法getOrElse(键值,没有时返回-1)
res44: Int = -1