nopens
nopens

Reputation: 761

Shorter way to check for not null for multiple variables

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;

Upvotes: 7

Views: 1617

Answers (5)

andreoss
andreoss

Reputation: 1800

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

Upvotes: 0

Amad&#225;n
Amad&#225;n

Reputation: 748

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

Upvotes: 5

John Arnok
John Arnok

Reputation: 632

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

Upvotes: 1

maio290
maio290

Reputation: 6732

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

Upvotes: 7

lczapski
lczapski

Reputation: 4120

You can use Stream and do like this:

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

Upvotes: 9

Related Questions