I wrote a function for checking if a Map[(String, String)]
contains an element with a matching key and value:
def findDupes(map: Map[String, String], key: String, value: String):
Option[(String, String)] = {
val dupes = map.collect { case (x, y) if(x == key && y == value) => key }
dupes match {
case Nil => None
case x :: _ => Some(key, value)
}
}
Testing
scala> map
res10: scala.collection.immutable.Map[String,String] = Map(1 -> HELLO, 2 -> WORLD)
scala> findDupes(map, "1", "HELLO")
res8: Option[(String, String)] = Some((1,HELLO))
scala> findDupes(map, "1", "FOO")
res9: Option[(String, String)] = None
2 Answers 2
Use map get key contains value
, to test if a given key-value-pair is already part of a Map
.
Your solution is extremely inefficient, because you iterate through the entire Map
(with collect
) just to find one value. get
returns an Option
which can be checked for the containing value.
collectFirst
will not necessarily iterate through the whole collection and will also return an Option so you don't have to do the pattern match:
def findDupes(map: Map[String, String], key: String, value: String): Option[(String, String)] = {
map.collectFirst( {case (`key`,`value`) => (key,value)})
}
map
in your example of use? \$\endgroup\$map
's definition. Thanks! \$\endgroup\$