scala:元组和映射
元组:
元祖即n个对象的聚集。
scala> (1, 2.0, "a", 'b')
res131: (Int, Double, String, Char) = (1,2.0,a,b)
//类型也可写为Tuple4[Int, Double, String, Char]
访问元组的元素,从1开始而不是0:
res131._1
res131 _4
用模式匹配访问元组各个元素:
scala> val (e1, e2, _, _) = res131
e1: Int = 1
e2: Double = 2.0
元组可用于函数返回值,可以返回多个值。
对偶:
n=2的元组
scala> val t1 = "a" -> 1
t1: (String, Int) = (a,1)
scala> val t2 = ('b', 2)
t2: (Char, Int) = (b,2)
映射
对偶的集合
scala> val score = Map(t1, t2) //不可变映射
score: scala.collection.immutable.Map[Any,Int] = Map(a -> 1, b -> 2)
scala> import scala.collection.mutable.Map //可变映射
import scala.collection.mutable.Map
scala> Map(t1,t2)
res98: scala.collection.mutable.Map[Any,Int] = Map(b -> 2, a -> 1)
查找映射中的值
score("a") //相当于java中map.get("a"),但是若不存在映射则抛出NoSuchElementException异常
score.getOrElse('c',1) //若不存在映射则赋值1
scala> score.get("b")
res104: Option[Int] = None
scala> score.get("a")
res105: Option[Int] = Some(1)
修改映射
只有可变映射才可以改变里面对偶的值:
res98("a") = 10 //修改或增加值
res98 += ("c" -> 3, "d" -> 4) //修改或增加多个值
res98 -= "d" //移除对偶
对不可变的映射,可以在其基础上做出修改创建新的映射
val newScore1 = score + ("a" -> 7, "e" -> 9)
val newScore2 = score - ("a", "e")
遍历映射
for((k,v) <- score) 处理k和v...
scala默认映射是哈希表映射,还有按键顺序排列的SortedMap
和按照插入顺序访问的LinkedHashMap
import scala.collection.immutable.SortedMap
import scala.collection.mutable.LinkedHashMap
zip操作
scala> Array("a", "b", "c").zip(Array(0, 9, 8))
res137: Array[(String, Int)] = Array((a,0), (b,9), (c,8))
scala> res137.toMap
res138: scala.collection.immutable.Map[String,Int] = Map(a -> 0, b -> 9, c -> 8)