Check if Map is Empty in Groovy

Check if Map is Empty in Groovy

  • Groovy
  • 1 min read

In Groovy, a map is a collection of key-value pairs. It is similar to a dictionary in other programming languages. A map allows you to store and retrieve values based on a key. To check if a map is empty in Groovy, you can use the isEmpty() method. Here's an example:

Check if Map is Empty in Groovy Examples

def map = [:]
if (map.isEmpty()) {
  println "map is empty"
} else {
  println "map is not empty"
}

This code checks if the map map is empty. Since we initialize the map with an empty map literal ([:]), the map is empty. Therefore, the code will print "map is empty".

Here's another example that shows how to check if a map is empty after adding some elements to it:

def map = [:]
map.put("key1", "value1")
map.put("key2", "value2")
if (map.isEmpty()) {
  println "map is empty"
} else {
  println "map is not empty"
}

In this code, we add two elements to the map using the put() method. Since the map is not empty after adding the elements, the code will print "map is not empty".

Related:

  1. Check if String is Empty in Groovy
  2. Groovy Tutorial