這個問題在這里已經有了答案: 如何檢查Map中是否存在鍵或值? (5 個回答) 昨天關門。
我是 scala 的新手,我試圖弄清楚如果找不到 Map 鍵如何不出錯。我有這樣的地圖:
val dict_a = Map("apple" -> "198.0.0.1")
我想看看是否能夠檢查和分配 key 的值,或者分配 null 一些東西。Scala 的新手,所以不確定它是如何完成的。
我想做這樣的事情......
val inp = "apple"
val link = if (dict_a(inp)) dict_a(inp) else null
uj5u.com熱心網友回復:
以下是檢查密鑰是否存在的一些示例用法:
scala> val myMap = Map[String, Int]("hello" -> 34)
myMap: scala.collection.immutable.Map[String,Int] = Map(hello -> 34)
// lookup the key hello. Returns an Option which can denote a
// a value being present or not.. instead of using null.
scala> myMap.get("hello")
res1: Option[Int] = Some(34)
scala> myMap.get("hello").isDefined
res2: Boolean = true
// if key is not in map.. return this default value
// similar to your example
scala> myMap.getOrElse("hello", 0)
res3: Int = 34
scala> myMap.getOrElse("not-exist", 0)
res4: Int = 0
scala> myMap.updated("not-exist", 33)
res5: scala.collection.immutable.Map[String,Int] = Map(hello -> 34, not-exist -> 33)
// this .exists function allow you to inspect the key and the
// value, or both or neither...
scala> myMap.exists { case (k, v) => k == "hello" && v == 34 }
res10: Boolean = true
scala> myMap.exists { case (k, v) => k == "hello" }
res11: Boolean = true
scala> myMap.filterKeys(_ == "hello")
res13: scala.collection.immutable.Map[String,Int] = Map(hello -> 34)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/530961.html
標籤:斯卡拉
下一篇:確定日期在串列中是否連續
