Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 244
Steven Huwig Avatar asked Mar 04 '09 21:03

Steven Huwig


4 Answers

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;
}
like image 96
Michael Myers Avatar answered Nov 19 '22 10:11

Michael Myers


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

if (asList(a, b, c, d).contains(null)) {
like image 33
Tom Hawtin - tackline Avatar answered Nov 19 '22 09:11

Tom Hawtin - tackline


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.

like image 4
akuhn Avatar answered Nov 19 '22 11:11

akuhn


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)) { ... }
like image 2
wpodgorski Avatar answered Nov 19 '22 11:11

wpodgorski