Checking if a collection is empty in Java: which is the best method?
Asked Answered
I

13

101

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?

Induline answered 22/6, 2012 at 8:17 Comment(6)
why do you think "latter" is better?Fennelflower
Why not listname.isEmpty() ? isEmpty is a method in the Collection interfaceGerta
why do you say latter is better? just because it checks null?Bandbox
collection interface provide isEmpty() method for empty check.both ways are better u can go with any one as per choice.Bechtel
I think personal flavor has a way in this. CollectionUtils does 2 things in one call so it is easier for you as a developer. The latter gives you as a developer a little more work however you do save the computer a push of the collection ref on the stack and the whole stack work around it. Performance-wise, the latter will be slightly faster. Not that you'll notice.Asepsis
Hi there... am I the only one seeing this as a matter of legibility? The first one is obviously better for making the code way more legible. Which sentence makes you think less when reading that, the resolution of two operations combined with an and or simply reading isNotEmpty ?? We can talk long about the performance benefits of the latter, but as a matter of error proneness, the former is much more robust.Ogata
D
160

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.

Distill answered 22/6, 2012 at 8:23 Comment(3)
While the List.size()==0 vs List.isEmpty() performance argument is correct, this does not answer to the question regarding the use of Apache commons-collections CollectionUtils.isEmpty or CollectionUtils.isNotEmpty()Bleat
LinkedLists implement isEmpty as return size() == 0;, though.Cherimoya
@user3932000: Sure, I'd expect that to be the case for any implementation that does know the size in a cheap wayDistill
O
74

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())
Occupy answered 22/6, 2012 at 8:21 Comment(2)
The other advantage of using Apache commons-collections CollectionUtils.isEmpty (or CollectionUtils.isNotEmpty) is that your if condition has less branches, so it is easier to reach a good branch coverage in your tests. For example, Sonarqube reports a 75% coverage at best for if (list==null || list.isEmpty()) because you cannot have a list which is null and not empty at the same time.Bleat
@JulienKronegg I don't think I agree. list == null and list.isEmpty() are two different use-cases and we should have test cases defined for each condition. One test case should evaluate the case when list is null and other should evaluate the case when list is non-null but empty. Just reaching coverage is not the true intention of unit tests.Robbery
S
15

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()

Sulphurous answered 6/7, 2015 at 9:5 Comment(0)
S
13

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.

Scala answered 22/6, 2012 at 8:21 Comment(2)
20 years as a developer and the habit of using CollectionUtils made me lazy. Didn't even notice the standard List.isEmpty()! Never too old to learn. Thanks man! I will change this attitide of mine :-DAsepsis
List.isEmpty() is not the same as CollectionUtils.isEmpty()! The latter will handle the case where the collection is null, the former will throw an NPE.Burget
C
7

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.

Carrera answered 22/6, 2012 at 8:24 Comment(1)
There are collections where the size() method is O(n). It's generally expected that all isEmpty() implementations will be O(1).Tomlinson
W
7

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)

Witt answered 13/10, 2014 at 20:37 Comment(0)
R
3

A good example of where this matters in practice is the ConcurrentSkipListSet implementation in the JDK, which states:

Beware that, unlike in most collections, the size method is not a constant-time operation.

This is a clear case where isEmpty() is much more efficient than checking whether size()==0.

You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.

Romano answered 17/12, 2014 at 12:33 Comment(0)
C
0
isEmpty()

      Returns true if this list contains no elements.

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/List.html

Chinaware answered 22/6, 2012 at 8:19 Comment(0)
C
0

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.

Chloe answered 22/6, 2012 at 8:19 Comment(1)
but you can also write a util of your own that will do the same that the second option does. Choose between options should be reasonablePhobia
E
0

Use CollectionUtils.isEmpty(Collection coll)

Null-safe check if the specified collection is empty. Null returns true.

Parameters: coll - the collection to check, may be null

Returns: true if empty or null

Ensemble answered 11/7, 2017 at 11:9 Comment(0)
A
0

The org.apache.commons.collections4.CollectionUtils isEmpty() method is used to check any collections(List, Set, etc.) are empty or not. It checks for null as well as size of collections. The CollectionUtils isEmpty() is a static method, which accepts Collection as a parameter.

Adage answered 19/8, 2021 at 7:3 Comment(0)
N
-1
table.column = ANY(ARRAY[ :canEmptyArrayParameter ]::BIGINT[])

It helps me to check empty parameter of array

this parameter can be Collections.emptyList();

Niemann answered 12/7, 2022 at 8:56 Comment(0)
N
-9

To Check collection is empty, you can use method: .count(). Example:

DBCollection collection = mMongoOperation.getCollection("sequence");
    if(collection.count() == 0) {
        SequenceId sequenceId = new SequenceId("id", 0);
        mMongoOperation.save(sequenceId);
    }
Naivete answered 3/2, 2016 at 4:42 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.