Reputation: 1048
I would like to find an API like Apache Commons that will easily and always return a collection.
The intent is to produce code that doesn't require NPE checks or CollectionUtils.isNotEmpty checks prior to collection iteration. The assumption in the code is to always guarantee a list instance thus eliminating code complexity for every collection iteration.
Here's an example of a method, but I would like an API instead of rolling my own.
private List<Account> emptyCollection(
List<Account> requestedAccounts) {
if (CollectionUtils.isNotEmpty(requestedAccounts)) {
return requestedAccounts;
} else {
return new ArrayList<Account>();
}
}
I would like to find a generic API / method that could be used for any class generically.
Here are some of my research classes inside commons that may help me do the trick. http://commons.apache.org/collections/apidocs/org/apache/commons/collections/TransformerUtils.html
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html
Maybe the .collect might work using a transformer.
I'm open to using alternative API's as well.
Upvotes: 0
Views: 144
Reputation:
Your question is a bit hard to understand, Do you simply want to avoid NPE, or also want to avoid CollectionUtil.isNotEmpty ? The first is very easy, the second not so, because you essentially want to guarantee that your API will always return a Collection with at least one element. That is a business centric constraint IMO, and not something you can guarantee via an API contract.
If all you want to avoid is NPE, you can use java.lang.Collections.EMPTY_(SET|MAP|LIST), classes. But mind you , these are immutable, i.e. the calling code, can't add objects to a collection returned this way. If you want the calling code to mutate the Collection (i.e. add/remove/update elements), then you'll have to return a zero element concrete implementation of your LIST|MAP|SET etc.
Upvotes: 0
Reputation: 206916
Is this an example of what you mean?
public static <T> List<T> nullToEmpty(List<T> list) {
if (list != null) {
return list;
}
return Collections.emptyList();
}
Upvotes: 4