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

后端 未结 11 1628
醉话见心
醉话见心 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:56

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

提交回复
热议问题