views:

119

answers:

2

Is there an analogous method to StringUtils.defaultString for collections, so you can avoid checking for null value, since in most cases, the desired effect is the same as if it were an empty list?

e.g. to replace

if (list != null) {
 for (String item: list) {
  // ...
 }
}

with something like

for (String item: ListUtils.defaultList(list)) {
 // ...
}

Using the ternary operator is pretty ugly and cause unchecked casting errors:

List<String> safelista = (List<String>) (list != null ? list : Collections.emptyList());
List<String> safelistb = (list != null ? list : Collections.EMPTY_LIST);

Putting it inline is even uglier.

+3  A: 

Do you have control over the method which returns the list in question? If so, I'd change it so that it never returns null, but just an empty list for the case that. That's also more the normal convention.

BalusC
No, in this case it's a method parameter, although I agree this is a good convention. I always make sure to initialize my collection fields to the appropriate empty collection.
pimlottc
Then I'd go for just a nullcheck and if necessary throw `IllegalArgumentException`. Or (my recommendation) just ignore it all and assume that it is never null (document it in the method's javadoc though that it requires a non-null collection and may throw NPE or IAE for the case that).
BalusC
I use a precondition that the parameter cannot be null and force the caller to do the right thing... (so if(x list == null) throw new IllegalArgumentException("list cannot be null"); and then I never have to worry about nulls).
TofuBeer
+3  A: 

Instead of using the tertiary operator, you must define a helper function which uses if():

public static <T> List<T> nullToEmpty (List<T> list) {
    if (list == null)
       return Collections.emptyList(); // Can't use ?: here!
    return list;
}
Aaron Digulla
or, slightly more generally, `<T> List<T> nullToEmpty (List<? extends T> list)`
skaffman
Doesn't make sense in this case. I return exactly the same list.
Aaron Digulla