27

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?

palacsint
  • 28,416
  • 10
  • 82
  • 109
ams
  • 60,316
  • 68
  • 200
  • 288
  • 3
    Methods should not return `null` collections in the first place. – SLaks Feb 15 '13 at 21:26
  • 2
    I believe such a method can be easily written using `Collections.emptyList()`. – Danilo Piazzalunga Feb 15 '13 at 21:27
  • 1
    @SLaks agreed in principle but you can't control other peoples code :) – ams Feb 15 '13 at 21:35
  • One somewhat confusing way to protect yourself from code that returns `null` instead of an empty `Collection` is to use AspectJ and after-advice. Create a pointcut that matches execution of methods returning `Collection`, and return an empty `Collection` if the original return value is `null`. Repeat for `Map`, `List`, etc. Your colleagues may not appreciate this, however. – Eric Jablow Mar 24 '13 at 03:01

5 Answers5

28
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.

Community
  • 1
  • 1
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 3
    What a way to make simple task look complicated. Use apache collections ListUtils.emptyIfNull from comment below. reads way better. – Vasiliy Dec 18 '19 at 14:37
  • This is exactly why people make fun of Java. There are far more readable solutions given by others. – saran3h Jan 22 '22 at 06:05
27

Apache Collections 4 has a generic method ListUtils.emptyIfNull(List<T> list)

Here is the doc: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ListUtils.html

palacsint
  • 28,416
  • 10
  • 82
  • 109
Jeffrey
  • 1,068
  • 2
  • 15
  • 25
18

In Java 8 it is possible to use this:

Optional.ofNullable(foo.canReturnANullListOfStrings()).orElse(Collections.emptyList());
Vojta
  • 1,583
  • 17
  • 19
7

Update for Java 9: java.util.Objects.requireNonNullElse(collection, List.<T>of())

The <T> is still required.

Mateusz Stefek
  • 3,478
  • 2
  • 23
  • 28
1

So there does not exist a function to my knowledge of this sort. However writing one is trivial as you have shown above. The reasoning behind why it might not have been included is because null has a specific meaning and it might not be appropriate to return an empty Collection when one gets passed around. Generally (in my experience) when a null value enters the system something failed higher up the chain or an invalid value was not properly sanitized.

Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
  • Unfortunately I see it quite often in a generated wrapping e.g. some JSON. And construction like `for(String thing : someObjFromJson.getFoo().getBar().getListOfThings()) {...do stuff...}` becomes not trivial without such method. – kan Jul 04 '19 at 10:21