Search code examples
javaapache-commons

How to guarantee Java collection


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.


Solution

  • 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();
    }