Best practice to validate null and empty collection in Java

srk picture srk · Oct 4, 2012 · Viewed 336.4k times · Source

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
}

Answer

Jalayn picture Jalayn · Oct 4, 2012

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.