Chapter 4 -- Scala for the Impatient
Chapter 4 -- Scala for the Impatient
翟志军 发表于3年前
Chapter 4 -- Scala for the Impatient
  • 发表于 3年前
  • 阅读 23
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

摘要: Map & Tuple
    <!-- lang: scala -->
    /////////// map  ///////////////////
    // define a map, default type is a scala.collection.immutable.Map
    val map1 = Map("alice" -> 12, "bob" -> 30)
    // map1("alice") = 30
    
    var map11 = Map("alice" -> 12, "bob" -> 30)
    //map11("alice") = 23 
    // Above is a invalid statement as map1 is. So, identify "val" and "var" in this case is the same thing.
    
    
    val map2 = new scala.collection.mutable.HashMap[String, Int]
    // yep, this is a mutable map. So, what does "val" mean in this statement?
    map2("ui") = 34
    // So, map2 is a mutable variable whatever "val" or "var"
    
    // another way to define a map
    val map3 = Map(("alice", 23), ("bob", 30))
    
    // get value from a map
    val bobAge = map3("bob")
    val _bobAge = if(map3.contains("bob")) map3("bob") else 0
    val __bobAge = map3.getOrElse("bob", 0)
    
    // update map
    map2 += ("ux" -> 33, "leader" -> 40)
    map2 -= "ui"
    
    // iteration
    for((k, v) <- map2) println(k + ":" + v)
    for((k, v) <- map2) yield (v, k)
    
    // sorted map
    val sortedMap = scala.collection.immutable.SortedMap("alice" -> 10, "Fred" -> 7, "Bob" -> 3, "Cindy" -> 4)
    val months = scala.collection.mutable.LinkedHashMap("Jan"-> 1, "Feb" -> 2, "Mar" -> 3)
    
    
    /////////// tuple  ///////////////////
    (1, 3.14, "Fred")
    // Tuple3[Int, Double, java.lang.String]
    
    val t = (1, 3.14, "Fred")
    t._2 // value would be 3.14. So, tuple is 1 first.
    
    val (first, second, third) = t // first: Int = 1   second: Double = 3.14   third: String = Fred
    val (f, s, _) = t //f: Int = 1  s: Double = 3.14
    
    
    // zip method
    val symbols = Array("<", "-", ">")
    val counts = Array(2, 10, 2)
    val pairs = symbols.zip(counts) // Array(("<", 2), ("-", 10), (">", 2))
共有 人打赏支持
翟志军
粉丝 336
博文 75
码字总数 79851
作品 2
×
翟志军
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: