1. 映射
映射Java中的Map,即Key/Value的数据形式
-
映射的创建,有以下两种方法
scala> val map =Map("Lisa" -> 90 , "Hellen" -> 89)
map: scala.collection.immutable.Map[String,Int] = Map(Lisa -> 90, Hellen -> 89) scala> val map =Map("Lisa" -> 90 , "Hellen" -> 89)
map: scala.collection.immutable.Map[String,Int] = Map(Lisa -> 90, Hellen -> 89) -
映射内容的修改
scala中的映射分为可变和不可变的,由import的包决定;默认引入scala.collection.immutable.Map的包;
scala.collection.immutable.Map是不可变的;不可改变已有的Key值的Value,亦不可增加键值对
scala> map
res44: scala.collection.immutable.Map[String,Int] = Map(Lisa -> 90, Hellen -> 8) scala> map("Lisa") =100
<console>:15: error: value update is not a member of scala.collection.immutable
Map[String,Int]
map("Lisa") =100
^ scala> map("Bob") =100
<console>:15: error: value update is not a member of scala.collection.immutable
Map[String,Int]
map("Bob") =100scala.collection.mutable.Map这个包的Map是可变的;
scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map scala> val map2 = Map("Lisa"-> 95,"Helln"-> 85)
map2: scala.collection.mutable.Map[String,Int] = Map(Lisa -> 95,Helln -> 85) scala> map2("Lisa")=100 scala> map2
res49: scala.collection.mutable.Map[String,Int] = Map(Lisa -> 100,Helln -> 85) scala> map2 += ("Bob" -> 65)
res50: map2.type = Map(Bob -> 65, Lisa -> 100, Helln -> 85) scala> map2 += (("Bob",80))
res52: map2.type = Map(Bob -> 80, Lisa -> 100, Helln -> 85)getOrElse(Key,defaultValue),取Map中的相应的Key的Value值,若不存在,则返回默认值;值得注意的是并没有在Map的添加该记录
scala> map2.getOrElse
getOrElse getOrElseUpdate scala> map2.getOrElse("Alice",60)
res53: Int = 60 scala> map2
res54: scala.collection.mutable.Map[String,Int] = Map(Bob -> 80, Lisa -> 100, Helln -> 85)
2. 元组
映射是K/V对偶的集合,对偶是元组的最简单形式,元组可以装着多个不同类型的值;Map可以看做是装了对偶元组的集合
- 元组的创建
scala> val y =(1,"Lisa",90)
y: (Int, String, Int) = (1,Lisa,90) - 元组的取值,角标从1开始
scala> y._1
res56: Int = 1 scala> y._2
res57: String = Lisa scala> y._3
res58: Int = 90
3. 集合
Scala的集合有三大类:序列Seq、集Set、映射Map,所有的集合都扩展自Iterable特质
在Scala中集合有可变(mutable)和不可变(immutable)两种类型
3.1 序列
不可变:List
可变:ListBuffer