Scala学习笔记(三)—chapter3

时间:2022-12-25 10:33:38

1、定长数组Array和变长数组ArrayBuffer。变长数组又称数组缓冲。常用方法:
+= 在尾端添加元素,在尾端添加多个元素,以括号包起来
++= 在尾端追加任何集合,比如Array、List等
trimEnd 移除最后N个元素
insert 插入
remove 移除
toArray 把ArrayBuffer转为Array

2、构造映射的方式。->操作符看上去比圆括号更易读。

1)val scores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
scala> :paste
// Entering paste mode (ctrl-D to finish)
val scores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
scores.getOrElse("Alice", "")
// Exiting paste mode, now interpreting.
scores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 10, Bob -> 3, Cindy -> 8)
res0: Any = 10
2)val scores = Map(("Alice", 10), ("Bob", 3), ("Cindy", 8))
scala> :paste
// Entering paste mode (ctrl-D to finish)
val scores = Map(("Alice", 10), ("Bob", 3), ("Cindy", 8))
scores("Alice")
// Exiting paste mode, now interpreting.
scores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 10, Bob -> 3, Cindy -> 8)
res1: Int = 10

3、scala中,映射是对偶的集合。对偶简单地说是两个值构成的组,这两个值并不一定是同一个类型,比如(“Alice”, 10)。->操作符用来创建对偶。如“alice”-> 10 产生的值是:(“Alice”, 10)

4、获取映射中的值。
(1)使用()表示法来查找某个键对应的值。
(2)使用getOrElse 表示法查找某个键对应的值。

5、可变映射的更新、添加、移除

scala> :paste
// Entering paste mode (ctrl-D to finish)
var score = scala.collection.mutable.Map("tom" -> 88, "jim" -> 99)
score("jim") = 66
score += ("bob" -> 77)
score -= "jim"
// Exiting paste mode, now interpreting.
score: scala.collection.mutable.Map[String,Int] = Map(bob -> 77, tom -> 88)
res4: scala.collection.mutable.Map[String,Int] = Map(bob -> 77, tom -> 88)

6、元组是不同类型的值的聚集。可以用方法_1、_2、 _3访问其组元。元组的各组元从1开始,而不是0。

val t = (1, 3.14, "Fred")
t._2
t _2
结果:
t: (Int, Double, String) = (1,3.14,Fred)
res0: Double = 3.14
res1: Double = 3.14

7、拉链操作

val symbols = Array("<", "-", ">")
val counts = Array(2, 10, 2)
val pairs = symbols.zip(counts)
for ((k, v) <- pairs) println(k + v + " ")

习题:
Scala学习笔记(三)—chapter3

val price = scala.collection.mutable.Map("bag" -> 20, "pencil" -> 12)
for ((k, v) <- price) yield (k, 0.9 * v)
// Exiting paste mode, now interpreting.
price: scala.collection.mutable.Map[String,Int] = Map(pencil -> 12, bag -> 20)
res0: scala.collection.mutable.Map[String,Double] = Map(pencil -> 10.8, bag -> 18.0)

Scala学习笔记(三)—chapter3

def minmax(values : Array[Int]) = {
(values.min, values.max)
}

Scala学习笔记(三)—chapter3

def iteqgt(values : Array[Int], v : Int) = {
(values.count(_ < v), values.count(_ == v), values.count(_ > v))
}
iteqgt(Array(1, 3, 5, 7, 9), 3)

Scala学习笔记(三)—chapter3

"Hello".zip("World")
res0: scala.collection.immutable.IndexedSeq[(Char, Char)] = Vector((H,W), (e,o), (l,r), (l,l), (o,d))