简体   繁体   中英

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.

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

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, ie the calling code, can't add objects to a collection returned this way. If you want the calling code to mutate the Collection (ie add/remove/update elements), then you'll have to return a zero element concrete implementation of your LIST|MAP|SET etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM