Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Existing utility method to ensure that all collection elements are non null [closed]

Tags:

java

java-8

guava

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.

like image 683
Alex Shesterov Avatar asked Mar 13 '23 16:03

Alex Shesterov


1 Answers

If what you want is something like Objects.requireNonNull you can simply do this:

myCollection.forEach(Objects::requireNonNull);
like image 186
Hank D Avatar answered Apr 26 '23 22:04

Hank D