Scala Map: Check if a map is empty
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics