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
asked Aug 1, 2014 at 16:37
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Is it just me or I don't see the definition of the values of map in your example of use? \$\endgroup\$ Commented Aug 1, 2014 at 17:31
  • \$\begingroup\$ just added with map's definition. Thanks! \$\endgroup\$ Commented Aug 1, 2014 at 17:33

2 Answers 2

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.

answered Aug 1, 2014 at 17:59
\$\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)})
 } 
answered Aug 1, 2014 at 18:05
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.