scala学习之map和tuple

Map

  //不可变的Map
  val scores = Map("Alice" -> 3, "lucy" -> 6, "Lily" -> 9)

  //可变的
  scala.collection.mutable.Map("Alice" -> 3, "lucy" -> 6, "Lily" -> 9)

  var map = new mutable.HashMap[String, Int]
  map += ("cindy" -> 5)
  println(map)

  //操作Map
  println(scores("Alice"))
  //如果映射中不包含 该键 会抛出异常
  //检查map中是否含有某个键 可以使用contains 方法
  val score = if (scores.contains("lucy")) scores("lucy") else 0

  //或者
  scores.getOrElse("lucy", 0)

  map("cindy") = 10 //更新cindy的值
  map("lilei") = 8 //增加新的映射
  //也可以这样
  map +=("Bob" -> 5, "Fred" -> 7)

  map -= "lilei"
  //移除键值对
  /**
   * 不能update不可以变的map,但是可以得到一个新的map
   */

  val newScores = scores +("Bob" -> 5, "Fred" -> 7)

  //也可以如此
  var scoreses = Map("Alice" -> 3, "lucy" -> 6, "Lily" -> 9)
  scoreses = scoreses +("Bob" -> 5, "Fred" -> 7)
  //从不可变Map中移除值
  scoreses = scoreses - "lucy"
  //迭代
  for ((name, num) <- scoreses) println("name :" + name + " socre:" + num)
  //返回key值set集合
  println(scoreses.keySet)
  //获取所有的value
  for (v <- scoreses.values) println(v)
  //反转map
  var reverSocres = for ((name, num) <- scoreses) yield (num, name)
  println(reverSocres)

  //不可变的TreeMap
  SortedMap("Alice" -> 3, "lucy" -> 6, "Lily" -> 9)
tuple:

  //元组
  val t = (1,3.14,"scala")
  println(t._1)  //访问元组 从1开始
  val (first,second,third) = t //依次对first,second,third为1,3.14,"scala"
  val (f,s,_) = t //如果不需要全部的值可以如此写

  //zip 很像python中的zip函数
  val symbols = Array("<","-",">")
  val counts = Array(3,6,3)
  val pairs = symbols.zip(counts)
  for ((s,n) <- pairs) Console.print(s * n) //打印<<<------>>>





posted @ 2015-08-06 18:13  傾聽雨落  阅读(141)  评论(0编辑  收藏  举报