Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to check for not null for multiple variables

Tags:

java

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;
like image 780
nopens Avatar asked Jun 30 '20 09:06

nopens


People also ask

How to check if multiple variables are true in JavaScript?

To check if multiple variables are not null in JavaScript, use the && (and) operator to chain multiple conditions. When used with boolean values the && operator only returns true if both conditions are met. Copied!

What is the best way to know if all the variables in a class are null?

if(id == null) is the best method.


2 Answers

You can use Stream and do like this:

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

like image 168
lczapski Avatar answered Oct 10 '22 03:10

lczapski


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;
}
like image 43
maio290 Avatar answered Oct 10 '22 03:10

maio290