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.
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 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())
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();
}
I have some simple logic to check if the field is valid:
private boolean isValidIfRequired(Object value) {
return
(required && !isEmpty(value)) || !required;
}
it tells that the field is valid if it's either required and not empty or not required.
I don't like this required || !required part. Something with just required would be better.
How do I simplify this method to make it more readable and simple?
How 'bout:
private boolean isValidIfRequired(Object value) {
return !required || !isEmpty(value);
}
or (thanks, #Peter Lawrey)
private boolean isValidIfRequired(Object value) {
return !(required && isEmpty(value));
}
In either case, if required is false, the || or && expression will short-circuit and isEmpty will never be called. If required is true, the second half of the || or && will be evaluated, calling isEmpty and returning the (inverted) result of that call.
The expected return of isValidIfRequired() is to return true.
So the exceptional cases must be put at the beginning as guardian clausules:
private boolean isValidIfRequired(Object value) {
if (required && empty(value)) //guardian clausule
return false;
return true;
}
for me the above code is more human-readable than using together expresions containing ANDs ORs and negations