ArrayList.addAll的任何null安全替代?

我正在重构我编写的一些旧代码,我在这段代码上做了标记:

List 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,其中包含这里引用的所有列表,因为它们可以为null(它们是从一个封闭的源框架中提取出来的数据库,不幸的是如果他没有找到任何内容则为null),我需要每次检查集合是否为null时将它们添加到此池中,这看起来很奇怪。

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

只需编写一个小实用程序方法:

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

这样你就可以写:

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

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

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

listToBeAdded – 要添加其元素的列表。 listToBeAddedTo – 使用addAll向其添加元素的列表。

使用Java 8:

 List fullImagePool = Stream.of(style.getTestMH(), /* etc */) .filter(Objects::nonNull) .flatMap(l -> l.stream()) .collect(Collectors.toList()); 

这个重构干净利落

 for (OcmImageData elem : new List[] { style.getTestMH(), style.getTrousers() /* etc */}) { if (CollectionUtils.isNotEmpty(elem)) { fullImagePull.addAll(elem); } } 

要回答你原来的问题,不,你必须做自己的空检查。 你可以看到Guava的方法会抛出一个NPE ,Apache的方法显然要求输入不为null 。