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)
2. 元组
映射是K/V对偶的集合,对偶是元组的最简单形式,元组可以装着多个不同类型的值;Map可以看做是装了对偶元组的集合
- 元组的创建
1 scala> val y =(1,"Lisa",90) 2 y: (Int, String, Int) = (1,Lisa,90)
- 元组的取值,角标从1开始
1 scala> y._1 2 res56: Int = 1 3 4 scala> y._2 5 res57: String = Lisa 6 7 scala> y._3 8 res58: Int = 90
3. 集合
Scala的集合有三大类:序列Seq、集Set、映射Map,所有的集合都扩展自Iterable特质
在Scala中集合有可变(mutable)和不可变(immutable)两种类型
3.1 序列
不可变:List
可变:ListBuffer