1
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Is it just me or I don't see the definition of the values of map in your example of use? \$\endgroup\$ – Marc-Andre Aug 1 '14 at 17:31
  • \$\begingroup\$ just added with map's definition. Thanks! \$\endgroup\$ – Kevin Meredith Aug 1 '14 at 17:33
4
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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)})
  } 
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.