Check if List is Empty in Groovy

Check if List is Empty in Groovy

  • Groovy
  • 1 min read

In Groovy, a list is an ordered collection of elements. It is similar to an array in other programming languages. A list allows you to store and retrieve elements in a specific order. To check if a list is empty in Groovy, you can use the isEmpty() method. Here's an example:

Check if List is Empty in Groovy Examples

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

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

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

def list = []
list << "element1"
list << "element2"
if (list.isEmpty()) {
  println "list is empty"
} else {
  println "list is not empty"
}

In this code, we add two elements to the list using the << operator. Since the list is not empty after adding the elements, the code will print "list is not empty".

Related:

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