检查 Scala Map 键是否存在的正确方法是什么?



我是新来的scala,我正试图找出如何不出错,如果地图键没有找到。我有一个这样的地图:

val dict_a = Map("apple" -> "198.0.0.1")

我想看看是否能够能够检查和分配值为关键或否则分配空的东西。scala是新手,所以不知道它是怎么做的。

我想这样做....

val inp = "apple"
val link = if (dict_a(inp)) dict_a(inp) else null

下面是检查键是否存在的一些示例用法:

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)

相关内容

最新更新