Is there a utility method in Java which converts Boolean into boolean and automatically handles null reference to Boolean as false?
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);
}
Are you looking for a ready-made utility ? Then I think Commons-Lang BooleanUtils is the answer. It has a method
toBoolean(Boolean bool).
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();
}
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
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();
}
Related
I have a use-case where I want to return boolean value from the function
private boolean checkStatus(String param) {
return param != null ? randomBool() : true;
}
private boolean randomBool() {
// return true or false on the basis of some condition
}
I am getting complaint issue over true statement. What could be the other way to achieve the same?
Sonar issue: Redundant Boolean literals should be removed from expressions to improve readability.
Just change your code to the next:
param == null || randomBool()
I'm trying to write a boolean function that returns true or false.
private boolean isExist(Optional<List<Attributes>> attributes) {
if (attributes.get().stream().filter(att -> att.getAttributeName().equals("exist") && att.getAttributeValue().equals("true")).count() > 0) {
return true;
}
return false;
}
How can I make use of Boolean.parseBoolean instead att.getAttributeValue().equals("true")? Is there any advantage of using it?
You can (and should) map the Optional directly in case it's empty. Then you can pass Boolean.parseBoolean as a parameter to map.
return attributes.map(Attributes::stream)
.filter (att -> "exist".equals (att.getAttributeName()))
.map (Attribute::GetValue)
.map (Boolean::parseBoolean)
.orElse (false);
I think you can use:
if (attributes.isEmpty()) {
return false;
}
return attributes.get().stream().anyMatch(att ->
"exist".equals(att.getAttributeName()) &&
Boolean.parseBoolean(att.getAttributeValue())
);
How can I make use of Boolean.parseBoolean instead
att.getAttributeValue().equals("true")?
You can do it as follows:
private boolean isExist(Optional<Attributes> attributes)
{
if (attributes.get().stream().filter(att -> att.getAttributeName().equals("exist") && Boolean.parseBoolean(att.getAttributeValue())==true)).count() > 0) {
return true;
}
return false;
}
You need to check your optional first:
private boolean isExist(Optional<List<Attributes>> attributes) {
return attributes.map(list -> list.stream().anyMatch(YourClass::isMatch))
.orElse(false);
}
private static boolean isMatch(Attributes att) {
return att.getAttributeName().equals("exist") && Boolean.parseBoolean(att.getAttributeValue());
}
Because you are only interested on a single match you should use the anyMatch.
How can I make use of Boolean.parseBoolean instead att.getAttributeValue().equals("true")?
Is there any advantage of using it?
Yes,
public static boolean parseBoolean(String s) Parses the string
argument as a boolean. The boolean returned represents the value true
if the string argument is not null and is equal, ignoring case, to the
string "true".
With this method strings like "TruE" will be consider true, so you do not have to worry about upper and lower case stuff, and more important if you receive a null Boolean.parseBoolean(..) return False. Nevertheless, I think in your case, unless you have a good reason to not do it, the better option would actually be to change
att.getAttributeValue()
to return true of false instead of a String encoding a boolean.
I just wanted to return a boolean from an Optional object by doing a check on the getProductType() on the ProductDetails object as shown below:
public boolean isElectronicProduct(String productName) {
Optional<ProductDetails> optProductDetails = findProductDetails(productName);
if(optProductDetails.isPresent()) {
return optProductDetails.get().getProductType() == ProductType.ELECTRONICS;
}
return false;
}
Intellij complains stating that the above code can be replaced in functional style, is there really any way to simplify the above Optional object and return a boolean?
This is what you need:
return findProductDetails(productName)
.map(ProductDetails::getProductType)
.map(ProductType.ELECTRONICS::equals)
.orElse(false);
I prefer to split things out with the extra map call, rather than calling productDetails.getProductType() directly before the comparison. I think it's just slightly easier to read.
Change this:
if(optProductDetails.isPresent()) {
return optProductDetails.get().getProductType() == ProductType.ELECTRONICS;
}
return false;
To:
return optProductDetails
.filter(prodDet -> prodDet.getProductType() == ProductType.ELECTRONICS) // Optional<ProductDetails> which match the criteria
.isPresent(); // boolean
You can read more about functional-style operations on Optional values at: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
optProductDetails.map(d -> d.getProductType() == ProductType.ELECTRONICS) //Optional<Boolean>
.orElse(false); //Boolean
Hello I've written statement with Optional<Parameter> and i return true if Parameter is present and it's value is false.
public boolean getNoDailyAllowance(String code) {
Optional<Parameter> myParam = parameterDao.getCachedParameter(code);
return myParam.isPresent() && !myParam.get().currentValueBoolean();
}
I want to rewrite it something like this
return calcDailyAllowanceParam.map(parameter -> Boolean.parseBoolean(parameter.getCurrentValue())).orElse(false);
but i can't add ! operator before parameter.getCurrentValue() what i do incorrectly.
Here is the solution:
public boolean getNoDailyAllowance(final String code) {
return !parameterDao
.getCachedParameter(code)
.map(Parameter::currentValueBoolean)
.orElse(true);
}
Since parameter.getCurrentValue() returns String you cannot negate it using !.
You should use ! before boolean value only:
parameter -> ! Boolean.parseBoolean(parameter.getCurrentValue())
What is difference between TextUtils.isEmpty(string) and string.isEmpty?
Both do the same operation.
Is it advantageous to use TextUtils.isEmpty(string)?
Yes, TextUtils.isEmpty(string) is preferred.
For string.isEmpty(), a null string value will throw a NullPointerException
TextUtils will always return a boolean value.
In code, the former simply calls the equivalent of the other, plus a null check.
return string == null || string.length() == 0;
In class TextUtils
public static boolean isEmpty(#Nullable CharSequence str) {
if (str == null || str.length() == 0) {
return true;
} else {
return false;
}
}
checks if string length is zero and if string is null to avoid throwing NullPointerException
in class String
public boolean isEmpty() {
return count == 0;
}
checks if string length is zero only, this may result in NullPointerException if you try to use that string and it is null.
Take a look at the doc
for the String#isEmpty they specify:
boolean
isEmpty()
Returns true if, and only if, length() is 0.
and for the TextUtils.isEmpty the documentation explains:
public static boolean isEmpty (CharSequence str)
Returns true if the string is null or 0-length.
so the main difference is that using the TextUtils.isEmpty, you dont care or dont need to check if the string is null referenced or not,
in the other case yes.
TextUtils.isEmpty() is better in Android SDK because of inner null check, so you don't need to check string for null before checking its emptiness yourself.
But with Kotlin, you can use String?.isEmpty() and String?.isNotEmpty() instead of TextUtils.isEmpty() and !TextUtils.isEmpty(), it will be more reader friendly
So I think it is preferred to use String?.isEmpty() in Kotlin and TextUtils.isEmpty() in Android Java SDK
String?.isNullOrEmpty
might be what you are looking for