Utility method to convert Boolean into boolean and handle null in Java

38k Views Asked by At

Is there a utility method in Java which converts Boolean into boolean and automatically handles null reference to Boolean as false?

6

There are 6 best solutions below

0
On BEST ANSWER

How about:

boolean x = Boolean.TRUE.equals(value);

? That's a single expression, which will only evaluate to true if value is non-null and a true-representing Boolean reference.

5
On

On java 8 you can do:

static boolean getPrimitive(Boolean value) {
        return Optional.ofNullable(value).orElse(false);
}

You can also do:

static boolean getPrimitive(Boolean value) {
        return Boolean.parseBoolean("" + value);
}
2
On

This would be a method you could write that would do the trick. This would return false if the Boolean is null.

public static boolean toBooleanDefaultIfNull(Boolean bool) {
    if (bool == null) return false;
    return bool.booleanValue();
}
0
On

I don't know whether it exists or not. I'd write a one liner like:

public static boolean getPrimitiveBoolean(Boolean bool) {    
   return bool == null ? false : bool.booleanValue();
}
0
On

Are you looking for a ready-made utility ? Then I think Commons-Lang BooleanUtils is the answer. It has a method toBoolean(Boolean bool).

0
On

If you're golfing, an explicit null check followed by automatic unboxing is shorter than the canonical answer.

boolean b=o!=null&&o; // For golfing purposes only, don't use in production code