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

Viewed 105

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
...
}
2 Answers

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)) {
    ...
} 

Maybe using optionals looks nice?

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