任何空安全的替代ArrayList.addAll? [英] Any null safe alternative to ArrayList.addAll?

查看:580
本文介绍了任何空安全的替代ArrayList.addAll?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重构我的一些老code,我已经写了,我stumbeled这个code:

I was refactoring some old code of mine that I've written and I stumbeled on this code:

    List<OcmImageData> fullImagePool = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(style.getTestMH())) {
        fullImagePool.addAll(style.getTestMH());
    }
    if (CollectionUtils.isNotEmpty(style.getTrousers())) {
        fullImagePool.addAll(style.getTrousers());
    }
    if (CollectionUtils.isNotEmpty(style.getDetailRevers())) {
        fullImagePool.addAll(style.getDetailRevers());
    }
    if (CollectionUtils.isNotEmpty(style.getDetailCuffs())) {
        fullImagePool.addAll(style.getDetailCuffs());
    }
    if (CollectionUtils.isNotEmpty(style.getDetailInner())) {
        fullImagePool.addAll(style.getDetailInner());
    }
    if (CollectionUtils.isNotEmpty(style.getDetailMaterial())) {
        fullImagePool.addAll(style.getDetailMaterial());
    }
    if (CollectionUtils.isNotEmpty(style.getComposing())) {
        fullImagePool.addAll(style.getComposing());
    }
    ...

所以基本上我需要创建一个包含所有列表在这儿引用一个ArrayList,因为那些可以为空(他们取了从封闭了源代码架构的数据库,不幸的是它的零,如果他没有找到任何东西),我需要检查每次如果集合不为空,将它们添加到这个游泳池看起来只是奇怪。

So basically I need to create an ArrayList which contains all Lists here referenced, because those can be null (they are fetched out of the database from an closed sourced framework, and unfortunately its null if he doesn't find anything), I need to check everytime if the collection is not null to add them into this pool which looks just weird.

有一个库或集合框架的实用程序类,它给了我posibility到集合添加到另一个不执行空安全检查?

Is there a library or Collection-Framework utility class that gives me the posibility to add a collection to another without performing the null-safe check?

推荐答案

刚写一个小工具的方法:

Just write a small utility method:

public static <E> void addAllIfNotNull(List<E> list, Collection<? extends E> c) {
    if (c != null) {
        list.addAll(c);
    }
}

让你可以写:

List<OcmImageData> fullImagePool = new ArrayList<>();
addAllIfNotNull(fullImagePool, style.getTestMH());
addAllIfNotNull(fullImagePool, style.getTrousers());
addAllIfNotNull(fullImagePool, style.getDetailRevers());
// ...etc

这篇关于任何空安全的替代ArrayList.addAll?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆