val scores=Map("Alice"->10,"Bob"->3,"Cindy"->8)
// 獲取所有的key
val nameList=scores.map(_._1)
// map 函數返回List
println(nameList.getClass)
遍歷list中的元素
nameList.foreach((x:String)=>print(x+" "))
輸出 :Alice Bob Cindy
// 或取所有的value
val resultList=scores.map(_._2)
resultList.foreach {(x:Int)=>print(x+" ") }
輸出:10 3 8
對於Tuple可以使用一樣的方法
val scores=List((1,"Alice",10),(2,"Bob",30),(3,"Cindy",50))
// 獲取所有Tuples中的第三個元素
val scoreList=scores.map(_._3)
for (scores<-scoreList){
print(scores +" ")
}
反向操作可以使用zip,將兩個list轉化為一個map,其中一個list作為key,另一個作為value
val keyList=List("Alice","Bob","Cindy")
val valueList=List(10,3,8)
val scores=keyList.zip(valueList).toMap
println(scores)
// Map(Alice -> 10, Bob -> 3, Cindy -> 8)
