Scala Map: Check if a map is empty
Scala Map Exercise-2 with Solution
Write a Scala program to create a map and check if it is empty or not.
Sample Solution:
Scala Code:
object CheckMapEmptyExample {
def main(args: Array[String]): Unit = {
// Create an empty map
val map_data = Map.empty[String, Int]
// Check if the map is empty
val isEmpty = map_data.isEmpty
// Print the result
if (isEmpty) {
println("Map is empty.")
} else {
println("Map is not empty.")
}
}
}
Sample Output:
Map is empty
Explanation:
In the above exercise -
- First, we create an empty map "map_data" using the Map.empty method.
- To check if the map is empty, we use the isEmpty method, which returns true if the "map_data" is empty, and false otherwise. We store the results in the isEmpty variable.
- Finally, we use an if statement to print the result based on whether the map is empty or not.
Scala Code Editor :
Previous: Creating and adding key-value pairs.
Next: Find the size of a map.
What is the difficulty level of this exercise?
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://www.w3resource.com/scala-exercises/map/scala-map-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics