Is there a method like this one in the JDK or Google Guava
public static <T> Collection<T> safe(Collection<T> collection) {
if (collection == null) {
return new ArrayList<>(0);
} else {
return collection;
}
}
which makes it easy to not crash on a an enhanced loop if something returns a null list for example
for (String string : CollectionUtils.safe(foo.canReturnANullListOfStrings())) {
// do something
}
would not crash.
I looked around but could not find any such method, and I am wondering if I missed it or if there is a reason why such a handy method is not handy and therefore not included?
Objects.firstNonNull(list, ImmutableList.<Foo>of());
There's no need for a specialized method, and this is indeed the solution we recommend you use immediately whenever you get a potentially-null collection from a naughty API that ideally shouldn't do that in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With