10

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.

4 Answers 4

19

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, I just did some scouting around and found a couple of anyNull methods, but they seem to predate varargs.
I tried searching Google Code (code.google.com), but I'm not exactly sure how to formulate the search. The basic structure of the code would look something like this, but the names could be almost anything.
10

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

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

5 Comments

With a static import of java.util.Arrays.asList, I presume?
close to literate programming
A little slower, too, one would guess, but no external libraries and no figuring out where to put the anyNull method.
It can also be used as: if (List.of(a, b, c, d).contains(null)). But be aware that an instance of ImmutableCollections will be created
@DiegoSouza And the array is copied, but the big problem is List.of(a, b, c, d).contains(null) will never retain false - it will NPE.
4

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.

Comments

2

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)) { ... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.