Scala--Map操作

1、定义Map

1.1、定义不可变的Map也就是immutable

scala> val m = Map("Tom" -> 55,"Jak" -> 56,"Jim" -> 66)
m: scala.collection.immutable.Map[String,Int] = Map(Tom -> 55, Jak -> 56, Jim -> 66)

//通过->符号定义

-------------------------------------------------------------------------------

scala> val m = Map(("Tom",23),("Jack",45),("Tinna",66))
m: scala.collection.immutable.Map[String,Int] = Map(Tom -> 23, Jack -> 45, Tinna -> 66)

//通过元组的方式定义

------------------------------------------------------------------------------

1.2、定义可变的Mapmutable

scala> val m = scala.collection.mutable.Map("Tom" -> 55,"Jak" -> 56,"Jim" -> 66)
m: scala.collection.mutable.Map[String,Int] = Map(Jim -> 66, Tom -> 55, Jak -> 56)

//通过指定scala.collection.mutable.Map来定义可变的Map

============================================================

2、访问Map的元素

scala> m
res0: scala.collection.mutable.Map[String,Int] = Map(Jim -> 66, Tom -> 55, Jak -> 56)

scala> m("Tom")
res1: Int = 55

scala> m("Toms")
java.util.NoSuchElementException: key not found: Toms
at scala.collection.MapLike$class.default(MapLike.scala:228)
at scala.collection.AbstractMap.default(Map.scala:59)
at scala.collection.mutable.HashMap.apply(HashMap.scala:65)
... 32 elided

//直接获取Map的元素的value,但是一旦这个元素不存在不会报错,会报错

scala> m.get("Tom")
res2: Option[Int] = Some(55)

scala> m.get("Toms")
res6: Option[Int] = None

//通过get方法获取元素的值,一旦这个元素不存在的话就会返回None

scala> m.getOrElse("Tom",-1)
res4: Int = 55

scala> m.getOrElse("Toms",-1)
res7: Int = -1

//getOrElse方法,如果元素存在的话就会返回值,如果元素不存在的话就会返回-1

================================================================

3、修改Map元素的值,必须是mutable的Map才能修改

scala> m
res8: scala.collection.mutable.Map[String,Int] = Map(Jim -> 66, Tom -> 55, Jak -> 56)

scala> m("Tom") = 65

scala> m
res10: scala.collection.mutable.Map[String,Int] = Map(Jim -> 66, Tom -> 65, Jak -> 56)

//通过直接修改的方式修改元素的值

=================================================================

4、遍历Map的各个元素

scala> for(s <- m)println(s)
(Jim,66)
(Tom,65)
(Jak,56)

//通过for循环访问Map的各个元素的值

-----------------------------------------------------

scala> m.foreach(println)
(Jim,66)
(Tom,65)
(Jak,56)

//通过Map的foreach来访问Map的各个元素的值

=========================================

5、mutable 是 可变的 ,val 是不可变的,两者是否冲突?

两者是不会冲突的

上一篇:Leetcode-66. 加一


下一篇:csp-s模拟测试66