Is there a utility method in Java which converts Boolean
into boolean
and automatically handles null reference to Boolean
as false?
Utility method to convert Boolean into boolean and handle null in Java
38k Views Asked by ps-aux At
6
There are 6 best solutions below
5

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

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

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

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

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
How about:
? That's a single expression, which will only evaluate to
true
ifvalue
is non-null and a true-representingBoolean
reference.