1. Overview

In this tutorial, we’ll see different ways that we can query the mappings in a Scala Map.

2. Querying Mappings in Maps

Given an existing Scala Map, there are a few different checks we may want to perform:

  • if a given key exists
  • if a value exists in the Map
  • if a given mapping pair (key, value) exists

Next, let’s see how we can achieve this using the following Map:

scala> val m = Map(1 -> "a", 2 -> "b", 3 -> "c")
m: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b, 3 -> c)

2.1. Check if a Given Key Exists

This is the most common query we do on a Map. The easiest approach is to use the isDefinedAt() or contains() methods:

scala> m.isDefinedAt(1)
res0: Boolean = true

scala> m.isDefinedAt(4)
res1: Boolean = false

scala> m.contains(1)
res2: Boolean = true

scala> m.contains(4)
res3: Boolean = false

Alternatively, we can access the KeySet and query it as well:

scala> m.keySet.contains(1)
res4: Boolean = true

scala> m.keySet.contains(4)
res5: Boolean = false

In this approach, we get the Set of all keys of the Map, and then look for our specific key.

2.2. Check if a Given Value Exists

If we want to know if a given value exists in the map, we can query its values:

scala> m.values.exists(_ == "a")
res0: Boolean = true

scala> m.values.exists(_ == "d")
res1: Boolean = false

Another option is to just query the Map directly without asking for the values:

scala> m.exists(_._2 == "a")
res0: Boolean = true

scala> m.exists(_._2 == "d")
res1: Boolean = false

Let’s make this more readable:

scala> m.exists{ case(key, value) => value == "a" }
res2: Boolean = true

We should be aware that a Map may contain more than one entry with the specified value. In such cases, we need to adapt our code depending on our goal.

2.3. Check if a Given (key, value) Pair Exists

Finally, let’s see how we can check if the Map has a mapping with a specific key and value pair:

scala> m.exists{ case(key, value) => (key, value) == (1, "a") }
res0: Boolean = true

scala> m.exists{ case(key, value) => (key, value) == (1, "b") }
res1: Boolean = false

We can express this more succinctly:

scala> m.exists(pair => pair  == (1, "a"))
res2: Boolean = true

scala> m.exists(pair => pair  == (1, "c"))
res3: Boolean = false

3. Conclusion

In this article, we saw how to query a given Map to determine if a key, a value, or a key-value pair are present by using the available methods including. We discussed approaches using the Map.contains(), Map.values(), and Map.exists() methods.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.