This post will discuss how to check if a list is empty in Java.

1. Using List.isEmpty() method

A simple solution to check if a list is empty in Java is using the List’s isEmpty() method. It returns true if the list contains no elements. To avoid NullPointerException, precede the isEmpty method call with a null check.

Download  Run Code

Output:

The collection is empty

 
If you want to do the opposite, i.e., check if the list is not empty, you can use the following expression:

Download  Run Code

Output:

The collection is empty

2. Using Apache Commons Collections

To get a null-safe version of the isEmpty() method, you may want to use the CollectionUtils.isEmpty() method by Apache Commons Collections.

Download Code

Output:

The collection is empty

3. Check empty or null in List of Lists

To check for an empty list or a null value in a List of Lists, you can use Stream API. For instance,

Download  Run Code

Output:

The collection is empty

 
Another alternative is to use the contains() method that checks for the specified value in the list. It can be used as follows:

Download  Run Code

Output:

The collection is empty

That’s all about checking if a list is empty in Java.