Steven Huwig
Steven Huwig

Reputation: 20794

Is there a varargs null check function in Java or Apache Commons?

I've got four variables and I want to check if any one of them is null. I can do

if (null == a || null == b || null == c || null == d) {
    ...
}

but what I really want is

if (anyNull(a, b, c, d)) {
    ...
}

but I don't want to write it myself. Does this function exist in any common Java library? I checked Commons Lang and didn't see it. It should use varargs to take any number of arguments.

Upvotes: 10

Views: 5593

Answers (4)

wpodgorski
wpodgorski

Reputation: 805

In Java 8 you can do it in even more elegant way:

if (Stream.of(a, b, c, d).anyMatch(Objects::isNull)) { ... }

or you can extract it to a method:

public static boolean anyNull(Object... objects) {
    return Stream.of(objects).anyMatch(Objects::isNull);
}

and then use it in your code like this:

if (anyNull(a, b, c, d)) { ... }

Upvotes: 2

akuhn
akuhn

Reputation: 27803

You asked in the comments where to put the static helper, I suggest

public class All {
    public static final boolean notNull(Object... all) { ... }
}

and then use the qualified name for call, such as

assert All.notNull(a, b, c, d);

Same can then be done with a class Any and methods like isNull.

Upvotes: 4

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

The best you can do with the Java library is, I think:

if (asList(a, b, c, d).contains(null)) {

Upvotes: 10

Michael Myers
Michael Myers

Reputation: 192015

I don't know if it's in commons, but it takes about ten seconds to write:

public static boolean anyNull(Object... objs) {
    for (Object obj : objs)
        if (obj == null)
            return true;
    return false;
}

Upvotes: 19

Related Questions