Utility method to convert Boolean into boolean and handle null in Java
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.
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);
}
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
Are you looking for a ready-made utility ? Then I think Commons-Lang BooleanUtils is the answer. It has a method toBoolean(Boolean bool).