1. Using the Helper method
2. Using Apache commons library [Easiest]
Read Also: Check if HashMap is empty in Java
Let's dive deep into the topic:
Check if Collection is empty or null in Java with examples
1. Using Helper method
We can easily check whether a Collection is empty or null in Java using a helper method. We have created a helper method with the name isEmptyOrNull() that returns the boolean value as shown below in the example.
import java.util.Collection;
import java.util.ArrayList;
public class CollectionEmptyNull {
public static void main(String args[]) {
Collection collection = new ArrayList(20);
boolean result = isEmptyOrNull(collection);
System.out.println(result);
}
public static boolean isEmptyOrNull(final Collection c)
{
return (c.isEmpty() || c == null);
}
}
Output:
true
2. Using Apache commons library
Another way to check if Collection is empty or null is by using CollectionUtils class which is present in org.apache.commons.collections4 package is shown below in the example. You can download the apache commons library from here.
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionEmptyNull2 {
public static void main(String args[]) {
Collection collection = new ArrayList(20);
boolean result = CollectionUtils.isEmpty(collection);
System.out.println(result);
}
}
Output:
true
That's all for today. Please mention in the comments if you have any questions related to how to check if Collection is empty or null in Java with examples.