Best practice to validate null and empty collection in Java

后端 未结 9 1886
北海茫月
北海茫月 2020-12-12 10:57

I want to verify whether a collection is empty and null. Could anyone please let me know the best practice.

Currently, I am checking as below:



        
相关标签:
9条回答
  • 2020-12-12 11:09

    If you use Spring frameworks, then you can use CollectionUtils to check against both Collections (List, Array) and Map etc.

    if(CollectionUtils.isEmpty(...)) {...}
    
    0 讨论(0)
  • 2020-12-12 11:10

    Personally, I prefer to use empty collections instead of null and have the algorithms work in a way that for the algorithm it does not matter if the collection is empty or not.

    0 讨论(0)
  • 2020-12-12 11:13

    You can use org.apache.commons.lang.Validate's "notEmpty" method:

    Validate.notEmpty(myCollection) -> Validate that the specified argument collection is neither null nor a size of zero (no elements); otherwise throwing an exception.

    0 讨论(0)
  • 2020-12-12 11:16

    We'll check a Collection object is empty, null or not. these all methods which are given below, are present in org.apache.commons.collections4.CollectionUtils package.

    Check on List or set type of collection Objects.

    CollectionUtils.isEmpty(listObject);
    CollectionUtils.isNotEmpty(listObject);
    

    Check on Map type of Objects.

    MapUtils.isEmpty(mapObject);
    MapUtils.isNotEmpty(mapObject);
    

    The return type of all methods is boolean.

    0 讨论(0)
  • 2020-12-12 11:17

    For all the collections including map use: isEmpty method which is there on these collection objects. But you have to do a null check before:

    Map<String, String> map;
    
    ........
    if(map!=null && !map.isEmpty())
    ......
    
    0 讨论(0)
  • 2020-12-12 11:24

    If you need to check for null, that is the way. However, if you have control on this, just return empty collection, whenever you can, and check only for empty later on.

    This thread is about the same thing with C#, but the principles applies equally well to java. Like mentioned there, null should be returned only if

    • null might mean something more specific;
    • your API (contract) might force you to return null.
    0 讨论(0)
提交回复
热议问题