Is there an existing utility method in Java 8 standard library or in Guava which ensures that the collection is not null and every element (if any) is not null?
Like a "collection-version" of Objects.requireNonNull()
.
I couldn't find anything like this so far. For now I wrote a trivial utility function which does the job:
public static void requireAllNonNull(final Collection<?> collection) {
Objects.requireNonNull(collection, "Collection must not be null");
if (collection.stream().anyMatch(Objects::isNull)) {
throw new NullPointerException("Collection elements must not be null");
}
}
But the problem is that it has to be duplicated in different (unrelated) projects.
One alternative would be to only use Guava's immutable collections which don't allow null
values at all, but sometimes collections originate from other sources.
If what you want is something like Objects.requireNonNull
you can simply do this:
myCollection.forEach(Objects::requireNonNull);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With