Scala快速入门-4-常用映射和元组操作

Posted by Yezhiwei on January 3, 2018

知识点

  • 映射是键值对的集合
  • n个对象(并不一定要相同类型的对象)的集合,元组

映射

  • 构造一个不可变(默认)映射(构造一个不可变的Map[String, Int],其值不能被改变)
scala> val scores = Map("Alice" -> 90, "Bob" -> 88)
scores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 90, Bob -> 88)
  • 构造一个可变映射
scala> val scores1 = scala.collection.mutable.Map("Alice" -> 90, "Bob" -> 88)
scores1: scala.collection.mutable.Map[String,Int] = Map(Bob -> 88, Alice -> 90)
  • 构造一个空映射,需要选定一个映射实现并给出类型参数(注意最后是 方括号[] )
scala> val scores2 = new scala.collection.mutable.HashMap[String, Int]
scores2: scala.collection.mutable.HashMap[String,Int] = Map()
  • 使用()获取映射中的值某个键对应的值
scala> val aliceScore = scores("Alice")
aliceScore: Int = 90
  • 判断映射中是否包括某个指定键的值,用contains方法
scala> val bobScore = if(scores.contains("Bob")) scores("Bob") else 0
bobScore: Int = 88

// 简洁写法
scala> val bobScore1 = scores.getOrElse("Bob", 0)
bobScore1: Int = 88
  • 可变映射中更新某个映射中的值或添加一个新的映射关系
scala> val scores1 = scala.collection.mutable.Map("Alice" -> 90, "Bob" -> 88)
scores1: scala.collection.mutable.Map[String,Int] = Map(Bob -> 88, Alice -> 90)

scala> scores1("Bob") = 99

scala> scores1
res1: scala.collection.mutable.Map[String,Int] = Map(Bob -> 99, Alice -> 90)


// 如果key不存在,添加一个新的映射关系
scala> scores1("Fred") = 79

scala> scores1
res3: scala.collection.mutable.Map[String,Int] = Map(Bob -> 99, Fred -> 79, Alice -> 90)

  • 使用+=操作来添加多个关系(key不存在就添加,存在就更新)
scala> scores1 += ("Yezhiwei" -> 100, "Fred" -> 90)
res4: scores1.type = Map(Bob -> 99, Fred -> 90, Alice -> 90, Yezhiwei -> 100)

scala> scores1
res5: scala.collection.mutable.Map[String,Int] = Map(Bob -> 99, Fred -> 90, Alice -> 90, Yezhiwei -> 100)
  • 使用-=操作来移除某个键值对
scala> scores1 -= "Bob"
res6: scores1.type = Map(Fred -> 90, Alice -> 90, Yezhiwei -> 100)

scala> scores1
res7: scala.collection.mutable.Map[String,Int] = Map(Fred -> 90, Alice -> 90, Yezhiwei -> 100)
  • 不可变的映射可以有同样的操作,只是返回一个新的映射,而不会更新原对象

  • 遍历映射中的所有键值对

scala> for((k, v) <- scores)
     | println(k + ":" + v)
     
// 运行结果     
Alice:90
Bob:88
  • 像Java一样,keySet和values方法访问键或值
scala> scores1.keys
res9: Iterable[String] = Set(Fred, Alice, Yezhiwei)

scala> for(v <- scores.values) println (v)
90
88

元组

  • 元组是不同类型的值的聚集,元组的值是通过将单个的值包含在圆括号中构成的
scala> (1, 3.14, "Fred")
res11: (Int, Double, String) = (1,3.14,Fred)
  • 元组的各组元从1开始的,不是0。与数组和字符串中的位置不同
scala> (1, 3.14, "Fred")
res11: (Int, Double, String) = (1,3.14,Fred)

scala> res11._1
res12: Int = 1
  • 使用模式匹配来获取元组的组元
scala> val (first, second, third) = res11
first: Int = 1
second: Double = 3.14
third: String = Fred
  • 如果不需要所有的值,可以在相应位置上使用_占位
scala> val (first, second, _) = res11
first: Int = 1
second: Double = 3.14
  • 元组可以用于函数需要返回不止一个值的情况
scala> "Hello Scala".partition(_.isUpper)
res13: (String, String) = (HS,ello cala)

敬请期待下一篇~