user1635014 user1635014 - 1 year ago 114
Java Question

Best practice to validate null and empty of a collection in java

I want to verify whether a collection is empty and

. Could anyone please let me know the best practice.

Currently I am checking as below.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download