Check whether a list is empty in Java
This post will discuss different ways to check whether a list is empty in Java. A list is empty if and only if it contains no elements.
1. Using List.isEmpty() method
The recommended approach is to use the List.isEmpty() method to check for an empty list in Java. Following is a simple example demonstrating usage of this method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.ArrayList; import java.util.List; class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(); if (list == null) { System.out.println("List is null"); } if (list.isEmpty()) { System.out.println("List is empty"); } else { System.out.println("List is not empty or null"); } } } |
Instead of explicitly checking if the list is null or empty, you can combine the isEmpty() method with a null check in a single expression, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3); if (list == null || list.isEmpty()) { System.out.println("List is empty or null"); } } } |
Or, even better:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3); if (list != null && !list.isEmpty()) { System.out.println("List is not empty"); } } } |
2. Using List.size() method
Finally, you can use the List.size() method, which returns the total number of items in it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3); if (list != null && list.size() > 0) { System.out.println("List is not empty"); } else { System.out.println("List is empty or null"); } } } |
That’s all about checking whether a list is empty in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)