What is the best way to guard against null in a for loop in Java?
This seems ugly :
if (someList != null) {
for (Object object : someList) {
Use ArrayUtils.nullToEmpty from the commons-lang library for Arrays
for( Object o : ArrayUtils.nullToEmpty(list) ) {
// do whatever
}
This functionality exists in the commons-lang library, which is included in most Java projects.
// ArrayUtils.nullToEmpty source code
public static Object[] nullToEmpty(final Object[] array) {
if (isEmpty(array)) {
return EMPTY_OBJECT_ARRAY;
}
return array;
}
// ArrayUtils.isEmpty source code
public static boolean isEmpty(final Object[] array) {
return array == null || array.length == 0;
}
This is the same as the answer given by @OscarRyz, but for the sake of the DRY mantra, I believe it is worth noting. See the commons-lang project page. Here is the nullToEmpty API documentation and source
Maven entry to include commons-lang in your project if it is not already.
org.apache.commons
commons-lang3
3.4
Unfortunately, commons-lang doesn't provide this functionality for List types. In this case you would have to use a helper method as previously mentioned.
public static List nullToEmpty(List list)
{
if(list == null || list.isEmpty())
{
return Collections.emptyList();
}
return list;
}