Scala中的Map

//不可变构造映射
val scores = Map("Alice" -> 10,"Bob" -> 3,"Cindy" -> 8)

//可变映射
val scores2 = scala.collection.mutable.Map("Alice" -> 10,"Bob" -> 3,"Cindy" -> 8)

//空映射
val scores1 = new scala.collection.mutable.HashMap[String,Int]
//对偶
"alie" -> 10

//对偶元组
val scores3 = Map(("Alice",10),("Bob",4),("cd1",2))



//获取值
val bookScore = scores3("Bob")

//contains检测
val fredScore = if (scores.contains("Red"))scores("Red") else 0

//getOrElse替换检测
scores.getOrElse("Bob",3)

// 显示调用get,获得Option   Some  None
scores.get("Bob")
scores.get("Bob").get
scores.get("Fred")

//设置值 只能修改可变映射
//val scores4 = scala.collection.mutable.Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
//scores4("Bob")=11

// 不可变映射不能修改,但能够产生新映射
val newScores = scores +("Bob" -> 10,"Fred"-> 7)

//遍历
for((k,v)<- scores) println(k+"is mapped to " +v)

//Key的Set集合

scores.keySet

//遍历value
for (v <- scores.values) println(v)

//产生新的Map
for ((k,v)<- scores)yield (v,k)

// 排序
val scores4 = scala.collection.immutable.SortedMap("Alice" -> 10,
  "Fred" -> 7, "Bob" -> 3, "Cindy" -> 8)

// 双向链表HashMap
val months = scala.collection.mutable.LinkedHashMap("January" -> 1,
  "February" -> 2, "March" -> 3, "April" -> 4, "May" -> 5,
  "June" -> 6, "July" -> 7, "August" -> 8, "September" -> 9,
  "October" -> 10, "November" -> 11, "December" -> 12)

注意 , 不可变映射也可以调用方法 , 只不过产生新的映射 。新映射和老映射共享大部分结构。 可变映射是在原映射基础上进行修改

你可能感兴趣的:(Scala)