Is CollectionUtils.isNotEmpty() better than a null check?

58,906

Solution 1

No real advantages here. Even if there is, it would be extremely small. It just prevents the creation of an Iterator and executing a branch instruction, that's all there is to it.

This small advantage occurs only when the collection is empty. The following loop:

for (String str : coll) {
   ...
}

is equivalent to:

for (Iterator<String> iterator = col.iterator(); iterator.hasNext();) {
   String str = iterator.next();
   ...
}

When the collection is empty, the check on CollectionUtils.isNotEmpty(coll) prevents the loop from executing. Hence no Iterator is created in memory and no call to hasNext() is done. This is at the expense to a O(1) call to coll.isEmpty().

Solution 2

Decompiling reveals

public static boolean isEmpty(Collection coll) {
    return coll == null || coll.isEmpty();
}

Solution 3

As explained above it depends, what you want to test and how is your logic constructed.

Suppose your example

if (CollectionUtils.isNotEmpty(coll)) {
  for (String str : coll) {
     System.out.println("Branch 1. Collection is not empty.");
  }
}
else {
  System.out.println("Branch 2. Collection is empty.");
}

In this example, we can see, that always Branch1 or Branch2 is executed.

If we use null expression, the result will be different if coll is not null but empty

if (coll != null) {
  for (String str : coll) {
     System.out.println("Branch1. Collection is not empty.");
  }
}
else {
  System.out.println("Branch2. Collection is empty.");
}

If the collection coll is not null but it is empty, nor Branch1 either Branch2 is executed, because the condition coll != null is true, but in loop for there is not even one pass.

Of course, if expression coll != null && coll.isNotEmpty() doing the same work as CollectionUtils.isNotEmpty(coll).

Therefore it not advisable programming manner to use test on null in case of collections coll != null only. This is a case of poorly treated extreme conditions, which may be a source of unwanted result.

Solution 4

The issue is, that the collection can still be empty, when it is not null. So, in your case it depends on your preferences what you choose.

Share:
58,906
Trying
Author by

Trying

Trying to learn things!!!!!

Updated on July 09, 2022

Comments

  • Trying
    Trying almost 2 years

    Many advice to use CollectionUtils.isNotEmpty(coll) rather then coll != null in the below use case also.

    if (CollectionUtils.isNotEmpty(coll)) {
        for (String str : coll) {
        }
    }
    

    instead of

    if (coll != null) {
        for (String str : coll) {
        }
    }
    

    Is there any reason/advantage to use CollectionUtils.isNotEmpty(coll) instead of other here? Thanks.