Shorter way to check for not null for multiple variables

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

Tags:

Java