1. 程式人生 > >Scala學習筆記(五)—— 對映、元祖、集合

Scala學習筆記(五)—— 對映、元祖、集合

1. 對映

對映Java中的Map,即Key/Value的資料形式

  • 對映的建立,有以下兩種方法
    1 scala> val map =Map("Lisa" -> 90 , "Hellen" -> 89)
    2 map: scala.collection.immutable.Map[String,Int] = Map(Lisa -> 90, Hellen -> 89)
    3 
    4 
    5 scala> val map =Map("Lisa" -> 90 , "Hellen" -> 89)
    6 map: scala.collection.immutable.Map[String,Int] = Map(Lisa -> 90, Hellen -> 89)
  •  對映內容的修改

      scala中的對映分為可變和不可變的,由import的包決定;預設引入scala.collection.immutable.Map的包;

      scala.collection.immutable.Map是不可變的;不可改變已有的Key值的Value,亦不可增加鍵值對

     1 scala> map
     2 res44: scala.collection.immutable.Map[String,Int] = Map(Lisa -> 90, Hellen -> 8)
     3 
     4 scala> map("Lisa") =100
     5
    <console>:15: error: value update is not a member of scala.collection.immutable 6 Map[String,Int] 7 map("Lisa") =100 8 ^ 9 10 scala> map("Bob") =100 11 <console>:15: error: value update is not a member of scala.collection.immutable 12 Map[String,Int] 13 map("Bob") =100

     

     scala.collection.mutable.Map這個包的Map是可變的;

     1 scala> import scala.collection.mutable.Map
     2 import scala.collection.mutable.Map
     3 
     4 scala> val map2 = Map("Lisa"-> 95,"Helln"-> 85)
     5 map2: scala.collection.mutable.Map[String,Int] = Map(Lisa -> 95,Helln -> 85)
     6 
     7 scala> map2("Lisa")=100
     8 
     9 scala> map2
    10 res49: scala.collection.mutable.Map[String,Int] = Map(Lisa -> 100,Helln -> 85)
    11 
    12 scala> map2 += ("Bob" -> 65)
    13 res50: map2.type = Map(Bob -> 65, Lisa -> 100, Helln -> 85)
    14 
    15 scala> map2 += (("Bob",80))
    16 res52: map2.type = Map(Bob -> 80, Lisa -> 100, Helln -> 85)

     getOrElse(Key,defaultValue),取Map中的相應的Key的Value值,若不存在,則返回預設值;值得注意的是並沒有在Map的新增該記錄

    1 scala> map2.getOrElse
    2 getOrElse   getOrElseUpdate
    3 
    4 scala> map2.getOrElse("Alice",60)
    5 res53: Int = 60
    6 
    7 scala> map2
    8 res54: scala.collection.mutable.Map[String,Int] = Map(Bob -> 80, Lisa -> 100, Helln -> 85)