95

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Vikrant
  • 1,809
  • 1
  • 13
  • 18
  • 2
    why do you think "latter" is better? – ant Jun 22 '12 at 08:18
  • 3
    Why not `listname.isEmpty()` ? `isEmpty` is a method in the Collection interface – ccheneson Jun 22 '12 at 08:19
  • why do you say latter is better? just because it checks null? – chaosguru Jun 22 '12 at 08:23
  • 1
    collection interface provide isEmpty() method for empty check.both ways are better u can go with any one as per choice. – bNd Jun 22 '12 at 08:45
  • 2
    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. – Lawrence Mar 24 '15 at 10:00
  • 1
    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. – coya Nov 30 '16 at 11:47

13 Answers13

157

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.

River
  • 8,585
  • 14
  • 54
  • 67
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    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()` – Julien Kronegg Dec 12 '18 at 14:17
  • LinkedLists implement `isEmpty` as `return size() == 0;`, though. – user3932000 Dec 16 '18 at 18:17
  • @user3932000: Sure, I'd expect that to be the case for any implementation that *does* know the size in a cheap way – Jon Skeet Dec 16 '18 at 19:26
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())
River
  • 8,585
  • 14
  • 54
  • 67
alexey28
  • 5,170
  • 1
  • 20
  • 25
  • 5
    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. – Julien Kronegg Dec 12 '18 at 14:13
  • 1
    @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. – Agam Mar 02 '22 at 01:10
14

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

lxknvlk
  • 2,744
  • 1
  • 27
  • 32
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.

aaa
  • 786
  • 3
  • 14
  • 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 :-D – Lawrence Mar 24 '15 at 10:02
  • 15
    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. – Starkii May 27 '15 at 13:50
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.

Nitram
  • 6,486
  • 2
  • 21
  • 32
  • 1
    There are collections where the `size()` method is O(n). It's generally expected that all `isEmpty()` implementations will be O(1). – Mike Duigou Feb 15 '14 at 00:26
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)

Suren Konathala
  • 3,497
  • 5
  • 43
  • 73
2

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.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
0
isEmpty()

      Returns true if this list contains no elements.

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

user278064
  • 9,982
  • 1
  • 33
  • 46
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.

Zavior
  • 6,412
  • 2
  • 29
  • 38
  • 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 reasonable – Constantine Ch Jun 27 '23 at 08:58
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

Ash
  • 37
  • 4
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.

Usman Yaqoob
  • 535
  • 5
  • 13
-1
table.column = ANY(ARRAY[ :canEmptyArrayParameter ]::BIGINT[])

It helps me to check empty parameter of array

this parameter can be Collections.emptyList();

-8

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);
    }
TVT. Jake
  • 279
  • 2
  • 7