Question

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.

Was it helpful?

Solution

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

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

OTHER TIPS

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;
}

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.

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)) { ... }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top