creates Map
val weights = Map("cat" -> 10, "elephant" -> 200000) val weight = weights("elephant") println(weight)
val colors = Map(("bird", "blue"), ("fox", "red")) val result1 = colors("bird") println(result1)
adds key, value to map
val zoo = Map("frog" -> 1, "lion" -> 1) val all = zoo + ("zebra" -> 1)
iterate over all values.
zoo.keys.foreach(println(_)) for (value <- zoo.values) { println(value) }
getOrElse
// Use a default value if the key does not exist. val result3 = sizes.getOrElse("Small", 0) if (result3 == 0) { println("Zero, else value") }
val result2 = sizes.get("Large") if (result2.isDefined) { println(result2) val number = result2.get println(number) }
equals
val map1 = Map((10, true), (20, false)) val map2 = Map((20, false), (10, true)) val map3 = Map((20, true), (10, true)) // These two maps are structurally equal. if (map1.equals(map2)) { println("Maps equal") }
Output
Maps equal
原文地址:https://www.cnblogs.com/pocahontas/p/11405678.html
时间: 2024-10-14 16:14:38