# Finding Duplicate (Key, Value) in Map

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

• Is it just me or I don't see the definition of the values of map in your example of use? – Marc-Andre Aug 1 '14 at 17:31
• just added with map's definition. Thanks! – Kevin Meredith Aug 1 '14 at 17:33

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)})