w3resource

Scala map key check: Verify key existence in a map

Scala Map Exercise-8 with Solution

Write a Scala program to create a map and check if it contains a specific key.

Sample Solution:

Scala Code:

object CheckMapContainsKeyExample {
  def main(args: Array[String]): Unit = {
    // Create a map
    var color_map = Map("Red" -> 1, "Green" -> 2, "Blue" -> 3, "Orange" -> 4)
   
    // Print the original map
    println("Original map: " + color_map)

    // Check if the map contains a specific key
    val keyToCheck = "Blue"
    val containsKey = color_map.contains(keyToCheck)

    // Print the result
    if (containsKey) {
      println(s"The map contains the key '$keyToCheck'.")
    } else {
      println(s"The map does not contain the key '$keyToCheck'.")
    }
  }
}

Sample Output:

Original map: Map(Red -> 1, Green -> 2, Blue -> 3, Orange -> 4)
The map contains the key 'Blue'.

Explanation:

In the above exercise -

  • First, we create a map "color_map" using the Map constructor and provide key-value pairs.
  • To check if the map contains a specific key, we use the contains method and pass the key we want to check as an argument. The method returns true if the key is present in the map, and false otherwise. We store the result in the "containsKey" variable.
  • Finally, we use an if statement to print the result based on whether the map contains the key or not.

Scala Code Editor :

Previous: Key-value pair traversal.
Next: Validate value presence in a map.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/map/scala-map-exercise-8.php