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, CollectionUtils.isEmpty(Collection coll)
method which is Null-safe check if the specified collection is empty.
for this import org.apache.commons.collections.CollectionUtils
.
Maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
You could potentially write a helper method which returned an empty sequence if you passed in null:
public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
return iterable == null ? Collections.<T>emptyList() : iterable;
}
Then use:
for (Object object : emptyIfNull(someList)) {
}
I don't think I'd actually do that though - I'd usually use your second form. In particular, the "or throw ex" is important - if it really shouldn't be null, you should definitely throw an exception. You know that something has gone wrong, but you don't know the extent of the damage. Abort early.
for (Object object : someList) {
// do whatever
} throws the null pointer exception.
I have modified the above answer, so you don't need to cast from Object
public static <T> List<T> safeClient( List<T> other ) {
return other == null ? Collections.EMPTY_LIST : other;
}
and then simply call the List by
for (MyOwnObject ownObject : safeClient(someList)) {
// do whatever
}
Explaination:
MyOwnObject: If List<Integer>
then MyOwnObject will be Integer in this case.
With Java 8 Optional
:
for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
// do whatever
}