This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one of the shortest recipes, Recipe 11.21, “How to Test for the Existence of a Key or Value in a Scala Map”
Problem
You want to test whether a Scala 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.17, “Accessing Map Values” shows how to avoid an exception while accessing a map key
- Recipe 11.19, “Getting the Keys or Values from a Map” demonstrates the
valuesandvaluesIteratormethods
| this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |