11.20. Testing for the Existence of a Key or Value in a Map

Problem

You want to test whether a map contains a given key or value.

Solution

To test for the existence of a key in a map, use the contains method:

scala> val states = Map(
     |   "AK" -> "Alaska",
     |   "IL" -> "Illinois",
     |   "KY" -> "Kentucky"
     | )
states: scala.collection.immutable.Map[String,String] =
  Map(AK -> Alaska, IL -> Illinois, KY -> Kentucky)

scala> if (states.contains("FOO")) println("Found foo") else println("No foo")
No foo

To test whether a value exists in a map, use the valuesIterator method to search for the value using exists and contains:

scala> states.valuesIterator.exists(_.contains("ucky"))
res0: Boolean = true

scala> states.valuesIterator.exists(_.contains("yucky"))
res1: Boolean = false

This works because the valuesIterator method returns an Iterator:

scala> states.valuesIterator
res2: Iterator[String] = MapLike(Alaska, Illinois, Kentucky)

and exists returns true if the function you define returns true for at least one element in the collection. In the first example, because at least one element in the collection contains the String literal ucky, the exists call returns true.

Discussion

When chaining methods like this together, be careful about intermediate results. In this example, I originally used the values methods to get the values from the map, but this produces a new collection, whereas the valuesIterator method returns a lightweight iterator.

See Also

  • Recipe 11.16, shows how to avoid an exception while accessing ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.