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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值