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());
}
...
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.
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?
This refactors cleanly to
To answer your original question, no, you will have to do your own null check. You can see Guava's methods will throw an NPE, and Apache's methods explicitly require the input to be not null.