Scala学习笔记(4)

本篇主要介绍Map和Tuple。

4.1 构建一个Map

val scores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8) 
//这样构建的Map内容不可改变。

val scores = scala.collection.mutable.Map("Alice" -> 10, "Bob" -> 3, 
"Cindy" -> 8)
//可以改变内容的Map

val scores = new scala.collection.mutable.HashMap[String, Int]
//初始为空的Map,需要指定类型和实现方式

Scala中Map实际上是pairs的集合。pair是两个值的集合,这两个值可以是不同类型的。->操作符,构造出一个pair"Alice" -> 10的值为("Alice", 10)。上面的定义方式,等价于:

val scores = Map(("Alice", 10), ("Bob", 3), ("Cindy", 8))

4.2 访问Map中的值

val bobsScore = scores("Bob")

当map里不存在这个键时,会抛出异常。下面两种方式,可以避免异常。

val bobsScore = if (scores.contains("Bob")) scores("Bob") else 0
val bobsScore = scores.getOrElse("Bob", 0)
// If the map contains the key "Bob", return the value; otherwise, return 0.

4.3 更新Map中的值

scores("Bob") = 10
// Updates the existing value for the key "Bob" (assuming scores is mutable)
scores("Fred") = 7
// Adds a new key/value pair to scores (assuming it is mutable)

使用()修改或增加键值对。

scores += ("Bob" -> 10, "Fred" -> 7)
scores -= "Alice"

使用+=-=进行增加或删除。

val newScores = scores + ("Bob" -> 10, "Fred" -> 7) // New map with update
scores = scores + ("Bob" -> 10, "Fred" -> 7)
scores = scores - "Alice"

不可变的map不可以更新,但可以得到新的map。

4.4 遍历Map

for ((k, v) <- map) process k and v
scores.keySet // A set such as Set("Bob", "Cindy", "Fred", "Alice")
for (v <- scores.values) println(v) 
// Prints 10 8 7 10 or some permutation thereof

使用keySetvalues,单独遍历Map的键或值。

4.5 有序Map

val scores = scala.collection.immutable.SortedMap("Alice" -> 10, "Fred" -> 7, 
"Bob" -> 3, "Cindy" -> 8)

如果想根据插入的顺序访问key,使用LinkedHashMap

val months = scala.collection.mutable.LinkedHashMap("January" -> 1, 
"February" -> 2, "March" -> 3, "April" -> 4, "May" -> 5, ...)

4.6 Tuples

val t = (1, 3.14, "Fred")
val second = t._2 // Sets second to 3.14

使用_1, _2, _3,访问tuple中的元素。这里的编号是从1开始的

val (first, second, third) = t 
// Sets first to 1, second to 3.14, third to "Fred"
val (first, second, _) = t
// a: Int = 1
// b: Double = 3.14

上面这种方式,也可以获得tuple中元素的值。在不需要所有的值时,可以用_

4.7 Zipping

val symbols = Array("<", "-", ">") 
val counts = Array(2, 10, 2)
val pairs = symbols.zip(counts)
//yields an array of pairs, Array(("<", 2), ("-", 10), (">", 2))

//The pairs can then be processed together:
for ((s, n) <- pairs) Console.print(s * n) // Prints <<---------->>

toMap操作,可以将pairs的集合转为Map

keys.zip(values).toMap

你可能感兴趣的:(Scala学习笔记(4))