标签:
val scores = Map("Jim"->10, ("Tom",20), "Sam"->44) //key->value, (key,value)两种方式表示, 不可变映射, val s = scala.collection.mutable.Map("Jim"->10, ("Tom",20), "Sam"->44)//可变映射 val s1 = new scala.collection.mutable.HashMap[String, Int] //空的Map //scores.+=(("Lily"->10)) //不可变映射,map中不能新增元素 s.+=(("Lily"->10)) s1.+=(("Jim"->10)) println(scores) println(s) println(s1)
结果:
Map(Jim -> 10, Tom -> 20, Sam -> 44) Map(Jim -> 10, Tom -> 20, Lily -> 10, Sam -> 44) Map(Jim -> 10)
val scores = Map("Jim"->10, ("Tom",20), "Sam"->44) val score1 = scores("Lily") //直接通过()获取里面的值 val score2 = if(scores.contains("Lily")) scores("Lily") else 0 //判断是否存在,然后再取值 val score3 = scores.getOrElse("Lily",0) //通过getOrElse方法实现,不存在给默认值 println(score1) println(score2) println(score3)
可变映射
val scores = scala.collection.mutable.Map("Jim"->10, ("Tom",20), "Sam"->44) scores("Jim") = 11 //更新值 scores("Fred") = 33 //新增值 scores += ("Lily"->30, "Li"-> 27) //增加多个 scores.+=(("Zhao"->44)) scores -= "Jim" //删除元素 println(scores)
结果
Map(Li -> 27, Zhao -> 44, Fred -> 33, Tom -> 20, Lily -> 30, Sam -> 44)
不可变映射 通过声明var变量来重新赋值,完成元素的增、删
var scores = Map("Jim"->10, ("Tom",20), "Sam"->44) scores = scores +("Lily"-> 23) scores -= "Jim" println(scores)
结果
Map(Tom -> 20, Sam -> 44, Lily -> 23)
var scores = Map("Jim"->10, ("Tom",20), "Sam"->44) for((k, v) <- scores) println (k+","+v) for(i<- scores.keySet) print(i+" ") println() for(i<- scores.values) print(i+" ")
结果
Jim,10 Tom,20 Sam,44 Jim Tom Sam 10 20 44
val sortedScores = scala.collection.immutable.SortedMap("Jim"->10, ("Tom",20), "Sam"->44)
println(sortedScores)
结果
Map(Jim -> 10, Sam -> 44, Tom -> 20)
val tuple = (1, 3.14, "Hello") println(tuple._1) //访问第一个元组,下标值不是0而是1 val(first, second, _) = tuple //获取元组的元素 println(second)
结果
1 3.14
把元组的多个值绑定在一起
val symbols = Array("<","-",">") val counts = Array(2,10,2) val pairs = symbols.zip(counts) for((k,v)<- pairs) print(k * v)
结果
<<---------->>
参考《快学Scala》
标签:
原文地址:http://www.cnblogs.com/one--way/p/5799459.html