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.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
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 <E> List<E> nullToEmpty(List<E> list)
{
if(list == null || list.isEmpty())
{
return Collections.emptyList();
}
return list;
}