Shorter way to check for not null for multiple variables

Viewed 311

I have three Integer variables, where I am not allowed to change to primitive int and I need to check if at least one of them have a value greater than 0. Is there a shorter / cleaner way to rewrite my code below:

Integer foo = // null or some value
Integer bar = // null or some value
Integer baz = // null or some value

boolean atLeastOnePositive = (foo != null && foo > 0) || (bar != null && bar > 0) || (baz != null && baz > 0)

return atLeastOnePositive;
5 Answers

You can use Stream and do like this:

boolean atLeastOnePositive = Stream.of(foo, bar, baz)
  .anyMatch(value -> value != null && value > 0);

I guess a varargs method would be the cleanest way:

public static boolean atLeastOnePositive(Integer...integers)
{
    for(Integer integer : integers)
    {
        if(integer != null && integer > 0) return true;
    }
    
    return false;
}

If you don't want to introduce a new method with a generic solution to the problem, your way is perfectly fine and I don't see much room for improvement.

If you do want to introduce a new method, I'd suggest to combine the solutions of maio290 and Iczapski. When using a stream, filters enhance readability:

public static boolean containsAtleastOnePositive(final Integer... values) {
    return Arrays.stream(values).filter(Objects::nonNull)
                                .anyMatch(v -> v > 0);
}

You can use the method below to return true if var is positive and false if var is negative or null.

public boolean isPositive(Integer var) {
        return (0 < (var == null ? 0 : var));
}

Another way would be to use Optional<Integer> instead of nullable Integer variable:

final Optional<Integer> foo = Optional.of(-1);
final Optional<Integer> bar = Optional.of(2);
final Optional<Integer> baz = Optional.empty();
final boolean atLeastOnePositive = Stream.of(foo, bar, baz)
    .flatMap(Optional::stream)
    .anyMatch(x -> x > 0);
Related