user1635014 user1635014 - 1 month ago 7
Java Question

Best practice to validate null and empty of a 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
}

Answer

If you use the Apache 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.

Comments