StringUtils.defaultString euphemism for collections?
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 re开发者_运维知识库place
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.
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.
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;
}
精彩评论