Checking if a collection is empty in Java: which is the best method?
I have two ways of checking if a List is empty or not
if (CollectionUtils.isNotEmpty(listName))
and
if (listName != null && listName.size() != 0)
My arch tells me that the former is better than latter. But I think the latter is better.
Can anyone please clarify it?
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.
CollectionUtils.isNotEmpty
checks if your collection is not null and not empty. This is better comparing to double check but only if you have this Apache library in your project. If you don't then use:
if(list != null && !list.isEmpty())
Unless you are already using CollectionUtils I would go for List.isEmpty()
, less dependencies.
Performance wise CollectionUtils will be a tad slower. Because it basically follows the same logic but has additional overhead.
So it would be readability vs. performance vs. dependencies. Not much of a big difference though.
if (CollectionUtils.isNotEmpty(listName))
Is the same as:
if(listName != null && !listName.isEmpty())
In first approach listName
can be null and null pointer exception will not be thrown. In second approach you have to check for null manually. First approach is better because it requires less work from you. Using .size() != 0
is something unnecessary at all, also i learned that it is slower than using .isEmpty()
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.