我正在重构我编写的一些旧代码,偶然发现了这段代码:
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,其中包含此处引用的所有列表,因为这些列表可以为空(它们是从闭源框架中从数据库中获取的,不幸的是,如果他没有找到任何内容,则它为空),我需要每次检查集合是否不为空,将它们添加到这个池中,这看起来很奇怪。
是否有一个库或 Collection-Framework 实用程序类使我能够将一个集合添加到另一个集合而不执行空安全检查?
在 Java 8 中使用以下代码:-
Optional.ofNullable(listToBeAdded).ifPresent(listToBeAddedTo::addAll)
listToBeAdded - 要添加其元素的列表。
listToBeAddedTo - 使用 addAll 添加元素的列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)