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())
Related
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
In the below example , someObjects is a set. I am trying to return true if a condition matches within the loop , however this doesn't seem to compile. However when I just add "return" it works fine.What is the issue that I need to fix?
public boolean find(){
someObjects.forEach(obj -> {
if (some_condition_met) {
return true;
}
});
return false;
}
Compilation Errors
The method forEach(Consumer) in the type
Iterable is not applicable for the arguments ((
obj) -> {})
I guess you want to do this:
public boolean find(){
return someObjects.stream().anyMatch(o -> your_condition);
}
The forEach method in a Collection expects a Consumer which means a function that takes a value, but doesn't return anything. That's why you can't use return true; but a return; works fine.
I you want to break out of the loop when your condition is met, it's better to use a simple for(...) loop. I assumed that the type of obj is Object:
for (Object obj : someObjects) {
if (some_condition_met) {
return true;
}
}
return false;
forEach accepts a Consumer therefore you cannot pass in a behaviour that does not return void. you need to do something like:
return someObjects.stream().anyMatch(e -> condition);
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'm new to java and I"m need to write a method that translates a boolean true or false into a string "yes" or "no". I'm kinda lost.
public class Book
{
private String title;
private String author;
private String isbn;
private int pages;
private boolean pback;
private double price;
/**
* Constructor for objects of class Book
*/
public Book(String bookTitle, String bookAuthor, String bookCode, int bookPages, boolean paperback, double bookRetail)
{
// initialise instance variables
title = bookTitle;
author = bookAuthor;
isbn = bookCode;
pages = bookPages;
pback = paperback;
price = bookRetail;
}
public String translate(boolean trueorFalse)
{
if(pback = true)
{
??????;
}
else(pback = false)
{
???????;
}
}
boolean myBoolean = true;
String result = myBoolean ? "yes" : "no";
The conditional operator is your friend:
public static String translate(boolean trueOrFalse) {
return trueOrFalse ? "yes" : "no";
}
In general, if you find yourself writing:
SomeType x;
if (someCondition) {
x = someExpression;
} else {
x = someOtherExpression;
}
it's generally nicer to use:
SomeType x = someCondition ? someExpression : someOtherExpression;
The conditional operator makes sure that only one of someExpression or someOtherExpression is evaluated, so you can use method calls etc, confident that they won't be executed inappropriately.
Of course there are times when this gets too complicated - you need to judge the readability of each form for yourself.
There is a project from Apache Group called Apache Commons Lang for working with common Java classes like Boolean. Its BooleanUtils class has some nice methods to work with:
toStringOnOff(boolean bool) - converts a boolean to a String returning 'on' or 'off'
toStringOnOff(Boolean bool) - converts a Boolean to a String returning 'on', 'off' or null
toStringTrueFalse(boolean bool) - converts a boolean to a String returning 'true' or 'false'
toStringTrueFalse(Boolean bool) - converts a Boolean to a String returning 'true', 'false' or null
toStringYesNo(boolean bool) - converts a boolean to a String returning 'yes' or 'no'
toStringYesNo(Boolean bool) - converts a Boolean to a String returning 'yes', 'no' or null
In your example you should work with the toStringYesNo method.
boolean myBoolean = false;
String result = BooleanUtils.toStringYesNo(myBoolean);
System.out.println(result);
This will print
no
To add the library to your project just add it to your Maven pom.xml dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
if(pback == true)
{
return "yes";
} else {
return "no";
}
A couple of things to note:
equality is tested using ==, so you should write if ( a == b ) , not if ( a = b );
returning a value from a method is done using the keyword return followed by the value;
else does not take a supplementary argument, unless you want to say else if which then takes an expression similar to if, e.g. else if ( a ==b ).
if (pback) {
return "yes";
}
else {
return "no";
}
I feel like I'm missing something.
First, the parameter for your translate method is never used. You should fix that.
Second, do you need to use the String values "Yes" and "No" for conditionals? If not and you can just use the boolean version(and I see no reason that you couldn't) I suggest leaving the boolean.
You can then translate that boolean into "Yes" or "No" when it is outputted using something like the following code:
//say your boolean variable is called gotIt
if(gotIt == true) //you can also just say if(gotIt) here
{
//here you place the string where it needs to be, either output it or place it into a variable
System.out.println("Yes");
}
else
{
//same as above but for false
System.out.println("No");
}
}
The fact is it is much easier to use conditionals with boolean values as opposed to testing 2 strings for equivalence.
The above advices should do the job, but I would recommend you to use:
public String translate(boolean trueOrFalse)
{
return String.valueOf(trueOrFalse);
}
because later you can easily convert that back:
public boolean translateBack(String translation)
{
return Boolean.parseBoolean(translation);
}
but the translation string will be "true" of "false" :)
String yesNo(boolean b) {
String[] s = {"yes", "no"};
return b ? s[0] : s[1];
}
EDITED with correct return