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

后端 未结 11 1549
醉话见心
醉话见心 2020-12-01 01:27

I have two ways of checking if a List is empty or not

if (CollectionUtils.isNotEmpty(listName)) 

and

if (listName != null          


        
相关标签:
11条回答
  • 2020-12-01 01:34

    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

    0 讨论(0)
  • 2020-12-01 01:40

    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())
    
    0 讨论(0)
  • 2020-12-01 01:40

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

    0 讨论(0)
  • 2020-12-01 01:41

    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.

    0 讨论(0)
  • 2020-12-01 01:43

    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);
        }
    
    0 讨论(0)
  • 2020-12-01 01:45

    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.

    0 讨论(0)
提交回复
热议问题