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

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

问题描述

我正在重构我编写的一些旧代码,并且偶然发现了这段代码:

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.

是否有一个库或 Collection-Framework 实用程序类可以让我在不执行空安全检查的情况下将一个集合添加到另一个集合中?

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?

推荐答案

在 Java 8 中使用以下代码:-

In Java 8 Use below code:-

Optional.ofNullable(listToBeAdded).ifPresent(listToBeAddedTo::addAll)

listToBeAdded - 要添加其元素的列表.listToBeAddedTo - 使用 addAll 添加元素的列表.

listToBeAdded - The list whose elements are to be added. listToBeAddedTo - The list to which you are adding elements using addAll.

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

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