Determine if a Collection (Set, List, Map, etc) is empty in Java
This post will discuss how to check if a Collection (Set, List, Map, etc.) is empty in Java.
1. Using isEmpty() method
The standard solution to check if a Java Collection is empty is calling the isEmpty() method on the corresponding collection. It returns true if the collection contains no elements.
The following solution provides the custom implementation of isEmpty() and isNotEmpty() methods, that handles null input gracefully.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Set; public class Main { public static boolean isNotEmpty(Set<Integer> set) { return set != null && !set.isEmpty(); } public static boolean isEmpty(Set<Integer> set) { return set == null || set.isEmpty(); } public static void main(String[] args) { Set<Integer> set = Set.of(); System.out.println(isNotEmpty(set) ? "Non-empty": "Empty"); } } |
Output:
false
2. Using Apache Commons Collections
Another approach is to use the CollectionUtils.isEmpty() method provided by Apache Commons Collections, which is the null-safe wrapper over the Collection.isEmpty() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import org.apache.commons.collections4.CollectionUtils; import java.util.Set; public class Main { public static void main(String[] args) { Set<Integer> set = Set.of(); System.out.println(CollectionUtils.isEmpty(set) ? "Empty": "Non-empty"); } } |
Output:
false
3. Using Apache Commons Lang
Apache Commons Lang provides ObjectUtils.isEmpty() method that returns true if an Object is empty or null; false otherwise.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import org.apache.commons.lang3.ObjectUtils; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> set = List.of(); System.out.println(ObjectUtils.isEmpty(set) ? "Empty": "Non-empty"); } } |
Output:
false
The ObjectUtils.isEmpty() method is implemented as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static boolean isEmpty(Object object) { if (object == null) { return true; } else if (object instanceof CharSequence) { return ((CharSequence)object).length() == 0; } else if (object.getClass().isArray()) { return Array.getLength(object) == 0; } else if (object instanceof Collection) { return ((Collection)object).isEmpty(); } else { return object instanceof Map ? ((Map)object).isEmpty() : false; } } |
That’s all about checking if a Collection 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 :)