映射:
def constructMap = {
//構造一個不可變Map[String Int]
val scores = Map("Alice" -> 10, "aaa" -> 9, "bbb" -> 5)
//構造一個可變Map[String,Int]
val mscores1 = scala.collection.mutable.Map("Alice" -> 10, "aaa" -> 9, "bbb" -> 5)
val mscores2 = scala.collection.mutable.Map(("Alice", 10), ("aaa", 9), ("bbb", 8))
}
def curdMap = {
val scores = scala.collection.mutable.Map("Alice" -> 10, "aaa" -> 9, "bbb" -> 5)
println(scores.mkString("<", ",", ">"))//輸出:<bbb -> 5,aaa -> 9,Alice -> 10>
//val bobScore = scores("Bob") //找不到拋異常
val aliceScore = scores("Alice")
val bobScore = scores.getOrElse("Bob", 6)
println(aliceScore)//輸出:10
println(bobScore)//輸出:6
scores("Alice") = 9
println(scores("Alice"))//輸出:9
scores += ("Bob" -> 7)
println(scores.mkString("<", ",", ">"))//輸出:<bbb -> 5,Bob -> 7,aaa -> 9,Alice -> 9>
scores -= "Bob"
println(scores.mkString("<", ",", ">"))//輸出:<bbb -> 5,aaa -> 9,Alice -> 9>
}
def traverseMap = {
val mapping = Map("Alice" -> 10, "aaa" -> 9, "bbb" -> 5)
val a = for ((k, v) <- mapping) yield k + ":" + v
println(a)//輸出:List(Alice:10, aaa:9, bbb:5)
val b = for (k <- mapping.keys) yield k
println(b)//輸出:Set(Alice, aaa, bbb)
val c = for (v <- mapping.values) yield v
println(c)//輸出:List(10, 9, 5)
}
def sortedMap = {
//scala自己只有不可變排序Map(樹形Map)
val mapping = SortedMap("Alice" -> 10, "aaa" -> 9, "bbb" -> 5)
println(mapping.mkString("<", ",", ">"))//輸出:<Alice -> 10,aaa -> 9,bbb -> 5>
}
元組:
def test = {
val tuple1 = (1, 2, 3, 9.0, "hello")
val element1 = tuple1._1
println(element1)//輸出:1
val (_, second, third, _, _) = tuple1
println(second)//輸出:2
println(third)//輸出:3
}
鏈式操做:
def test = {
val key = Array("zhx", "dick", "hash")
val value = Array(1, 2, 3)
val keyvalue = key.zip(value)
val map = keyvalue.toMap
println(map.mkString("<", ",", ">"))//輸出:<zhx -> 1,dick -> 2,hash -> 3>
}