I have two ways of checking if a List is empty or not
if (CollectionUtils.isNotEmpty(listName))
and
if (listName != null
I would use the first one. It is clear to see right away what it does. I dont think the null check is necessary here.
You should absolutely use isEmpty()
. Computing the size()
of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size()
which can't also make isEmpty()
faster, whereas the reverse is not the case.
For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E>
does). Then size()
would become an O(N) operation, whereas isEmpty()
would still be O(1)
.
Additionally of course, using isEmpty()
states what you're actually interested in more clearly.
isEmpty()
Returns true if this list contains no elements.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/List.html
Apache Commons' CollectionUtils.isNotEmpty(Collection) is a NULL-SAFE check
Returns TRUE is the Collection/List is not-empty and not-null Returns FALSE if the Collection is Null
Example:
List<String> properties = new ArrayList();
...
if (CollectionUtils.isNotEmpty(properties)) {
// process the list
} else {
// list is null or empty
}
Refer: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isNotEmpty(java.util.Collection)
If you have the Apache common utilities in your project rather use the first one. Because its shorter and does exactly the same as the latter one. There won't be any difference between both methods but how it looks inside the source code.
Also a empty check using
listName.size() != 0
Is discouraged because all collection implementations have the
listName.isEmpty()
function that does exactly the same.
So all in all, if you have the Apache common utils in your classpath anyway, use
if (CollectionUtils.isNotEmpty(listName))
in any other case use
if(listName != null && listName.isEmpty())
You will not notice any performance difference. Both lines do exactly the same.