w3resource

Scala map value check: Validate value presence in a map

Scala Map Exercise-9 with Solution

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

Sample Solution:

Scala Code:

object CheckMapContainsValueExample {
  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 value
    val valueToCheck = 3
    val containsValue = color_map.values.exists(_ == valueToCheck)

    // Print the result
    if (containsValue) {
      println(s"The map contains the value '$valueToCheck'.")
    } else {
      println(s"The map does not contain the value '$valueToCheck'.")
    }
  }
}

Sample Output:

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

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 value, we use the values method to obtain a collection of all the values in the map. We then use the exists method on the collection and pass a predicate function that checks if any value is equal to the value we want to check. The exists method returns true if such a value exists, and false otherwise. We store the result in the containsValue variable.
  • Finally, we use an if statement to print the result based on whether the map contains the value or not.

Scala Code Editor :

Previous: Verify key existence in a map.
Next: Find the minimum value.

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-9.php