Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
In this tutorial, we’ll see different ways that we can query the mappings in a Scala Map.
Given an existing Scala Map, there are a few different checks we may want to perform:
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)
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.
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.
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
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.