首页 > 代码库 > 快学Scala 第五课 (构造映射,获取映射值,更新映射值,迭代映射,与Java互操作)

快学Scala 第五课 (构造映射,获取映射值,更新映射值,迭代映射,与Java互操作)

构造映射:

    val score = Map[String, Int]()
    val score1 = HashMap[String, Int]()
    
    val value1 = Map[String, Int]("aa" -> 1, "bb" -> 2)
    val value2 = Map[String, Int](("aa", 1), ("bb", 2))

获取映射值:

    println(if(value2.contains("cc")) value2("cc") else 0)
    println(value2.getOrElse("cc", 0))
    println(value2.getOrElse("aa", 0))

更新映射值:

    score1("aa") = 1
    score1("bb") = 2
    score1 += ("cc" -> 3, "dd" -> 4)
    score1 += (("cc", 3), ("dd", 4))
    score1 -= "cc"

迭代映射:

    for((k,v) <- value2){
      println(k)
      println(v)
    }
    
    value2.keySet
    println(value2.values)
    
    for (v <- value2.values) println(v)
    
    println(for ((k, v) <- value2 ) yield {(v, k)})

与Java互操作:(java.util.Properties 转 scala.collection.mutable.Map)

   val prop = new Properties()
    prop.put("aaa", "1")
    prop.put("bba", "2")
    
    import scala.collection.JavaConversions.propertiesAsScalaMap
    val scalaMap: scala.collection.mutable.Map[String, String] = prop
    scalaMap.foreach(println)

  

快学Scala 第五课 (构造映射,获取映射值,更新映射值,迭代映射,与Java互操作)