NutellaAddict
NutellaAddict

Reputation: 584

Elegant way to check if two Booleans are equal, with a caveat where False==null?

I'm currently just normalizing nulls to Boolean.FALSE, then doing the check. But is there some util that does this cleanly?

Refactoring to boolean is not an option as these variables come from an external object parameter, where False is equivalent to null.

Example:

Boolean A = null;
Boolean B = Boolean.FALSE;

if(Objects.equals(A,B)){ //should return true
...
}

Upvotes: 2

Views: 373

Answers (2)

Vladislav Varslavans
Vladislav Varslavans

Reputation: 2934

Maybe using optionals looks nice?

Optional.ofNullable(A).orElse(Boolean.FALSE).equals(B)

Upvotes: 0

khelwood
khelwood

Reputation: 59104

Boolean.TRUE.equals(v) will evaluate to true if v is TRUE, and false if v is FALSE or null. Using that you can compare your two Boolean values (considering null and FALSE as equivalent) like this:

if (Boolean.TRUE.equals(a)==Boolean.TRUE.equals(b)) {
    ...
} 

Upvotes: 1

Related Questions