Using find function for maps in scala

You use the same kind of predicate as with a List, but keep in mind you're evaluating it over (key,value) pairs, instead of just values (and getting a pair back as well!).

Simple example:

val default = (-1,"")
val value = "red"
colors.find(_._2==value).getOrElse(default)._1

The signature for find in Map is find(p: ((A, B)) ⇒ Boolean): Option[(A, B)]. So the predicate takes a Tuple2 and must return a Boolean. Note I changed value to an Int since the key in colors is also an Int.

scala> def keyForValue(map: Map[Int, String], value: Int) = {
     | colors.find({case (a,b) => a  == value})
     | }
keyForValue: (map: Map[Int,String], value: Int)Option[(Int, String)]

Test:

scala> keyForValue(colors, 1)
res0: Option[(Int, String)] = Some((1,red))

You can also use get:

scala> colors.get(1)
res1: Option[String] = Some(red)

Tags:

Map

Scala