Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JDK or Guava method to turn a null into an empty list?

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?

like image 940
ams Avatar asked Sep 06 '25 12:09

ams


1 Answers

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.

like image 123
Louis Wasserman Avatar answered Sep 08 '25 04:09

Louis Wasserman