Best practice to validate null and empty collection in Java

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:

if (null == sampleMap || sampleMap.isEmpty()) {
  // do something
} 
else {
  // do something else
}

Solution 1:

If you use the Apache Commons Collections library in your project, you may use the CollectionUtils.isEmpty and MapUtils.isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").

The code behind these methods is more or less what user @icza has written in his answer.

Regardless of what you do, remember that the less code you write, the less code you need to test as the complexity of your code decreases.

Solution 2:

That is the best way to check it. You could write a helper method to do it:

public static boolean isNullOrEmpty( final Collection< ? > c ) {
    return c == null || c.isEmpty();
}

public static boolean isNullOrEmpty( final Map< ?, ? > m ) {
    return m == null || m.isEmpty();
}

Solution 3:

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

if(CollectionUtils.isEmpty(...)) {...}