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
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 understand you can't return from a ifPresent() so this example does not work:
public boolean checkSomethingIfPresent() {
mightReturnAString().ifPresent((item) -> {
if (item.equals("something")) {
// Do some other stuff like use "something" in API calls
return true; // Does not compile
}
});
return false;
}
Where mightReturnAString() could return a valid string or an empty optional. What I have done that works is:
public boolean checkSomethingIsPresent() {
Optional<String> result = mightReturnAString();
if (result.isPresent()) {
String item = result.get();
if (item.equals("something") {
// Do some other stuff like use "something" in API calls
return true;
}
}
return false;
}
which is longer and does not feel much different to just checking for nulls in the first place. I feel like there must be a more succinct way using Optional.
I think all you're looking for is simply filter and check for the presence then:
return result.filter(a -> a.equals("something")).isPresent();
How about mapping to a boolean?
public boolean checkSomethingIfPresent() {
return mightReturnAString().map(item -> {
if (item.equals("something")) {
// Do some other stuff like use "something" in API calls
return true; // Does not compile
}
return false; // or null
}).orElse(false);
}
While #nullpointer and #Ravindra showed how to merge the Optional with another condition, you'll have to do a bit more to be able to call APIs and do other stuff as you asked in the question. The following looks quite readable and concise in my opinion:
private static boolean checkSomethingIfPresent() {
Optional<String> str = mightReturnAString();
if (str.filter(s -> s.equals("something")).isPresent()) {
//call APIs here using str.get()
return true;
}
return false;
}
A better design would be to chain methods:
private static void checkSomethingIfPresent() {
mightReturnFilteredString().ifPresent(s -> {
//call APIs here
});
}
private static Optional<String> mightReturnFilteredString() {
return mightReturnAString().filter(s -> s.equals("something"));
}
private static Optional<String> mightReturnAString() {
return Optional.of("something");
}
The ideal solution is “command-query separation”: Make one method (command) for doing something with the string if it is present. And another method (query) to tell you whether it was there.
However, we don’t live an ideal world, and perfect solutions are never possible. If in your situation you cannot separate command and query, my taste is for the idea already presented by shmosel: map to a boolean. As a detail I would use filter rather than the inner if statement:
public boolean checkSomethingIfPresent() {
return mightReturnAString().filter(item -> item.equals("something"))
.map(item -> {
// Do some other stuff like use "something" in API calls
return true; // (compiles)
})
.orElse(false);
}
What I don’t like about it is that the call chain has a side effect, which is not normally expected except from ifPresent and ifPresentOrElse (and orElseThrow, of course).
If we insist on using ifPresent to make the side effect clearer, that is possible:
AtomicBoolean result = new AtomicBoolean(false);
mightReturnAString().filter(item -> item.equals("something"))
.ifPresent(item -> {
// Do some other stuff like use "something" in API calls
result.set(true);
});
return result.get();
I use AtomicBoolean as a container for the result since we would not be allowed to assign to a primitive boolean from within the lambda. We don’t need its atomicity, but it doesn’t harm either.
Link: Command–query separation on Wikipedia
By the way if you really want to get value from Optional, use:
Optional<User> user = service.getCurrentUset();
return user.map(User::getId);
I am a little confused on "how to do this properly":
// return true: if present and number of lines != 0
boolean isValid(Optional<File> optFile) {
return optFile.ifPresentOrElse(f -> return !isZeroLine(f), return false);
}
private boolean isZeroLine(File f) {
return MyFileUtils.getNbLinesByFile(f) == 0;
}
I know the syntax is not correct and not compiling, but it's just for you to get the idea.
How can I turn this into 'clean code'?
i.e. avoid doing:
if (optFile.isPresent()) {//} else {//}
Dealing with boolean return type(easily inferred Predicates), one way to do that could be to use Optional.filter :
boolean isValid(Optional<File> optFile) {
return optFile.filter(this::isZeroLine).isPresent();
}
But, then using Optionals arguments seems to be a poor practice. As suggested in comments by Carlos as well, another way of implementing it could possibly be:
boolean isValid(File optFile) {
return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
}
On another note, ifPresentOrElse is a construct to be used while performing some actions corresponding to the presence of the Optional value something like :
optFile.ifPresentOrElse(this::doWork, this::doNothing)
where the corresponding actions could be -
private void doWork(File f){
// do some work with the file
}
private void doNothing() {
// do some other actions
}
I have a sequence of methods that I need to run sequentially, using the result of each method as a parameter in the next. However, I also check that the result of each method is "good" before calling the next method (if it's "bad" then I exit the method early. The methods return an empty Optional if they were not successful.
Is there a refactoring that I can perform to improve the code? Chain of Responsibility feels a little overboard.
private boolean isSequenceSuccessful() {
Optional<byte[]> result1 = doSomething();
if (!result1.isPresent()) {
return false;
}
Optional<byte[]> result2 = doAnotherThing(result1.get());
if (!result2.isPresent()) {
return false;
}
Optional<byte[]> result3 = doSomethingElse(result2.get());
if (!result3.isPresent()) {
return false;
}
return doMoreStuff(result3.get());
}
I don't want to use Exceptions to control the flow of the method because that's a code smell (I expect to sometimes get "bad" results).
You can write it shorter using Optional and mapping:
private boolean isSequenceSuccessful() {
return Optional.of(doSomething())
.flatMap(result1 -> doAnotherThing(result1))
.flatMap(result2 -> doSomethingElse(result2))
.map(result3 -> doMoreStuff(result3))
.orElse(false);
}
Or using method references even shorter:
private boolean isSequenceSuccessful2() {
return Optional.of(doSomething())
.flatMap(this::doAnotherThing)
.flatMap(this::doSomethingElse)
.map(this::doMoreStuff)
.orElse(false);
}
It depends what you prefer. If you want to keep the intermediate result variables use the lambda version.
Since the methods doAnotherThing and doSomethingElse do return an Optional<byte[]>, Optional.flatMap is needed to continue the mapping. Otherwise you could change the return type of these methods to return byte[] solely. Then you would use Optinal.map only, which would be more consistent.
The mapping will only be performed as long as a value is present in the Optional. If all mappings could be applied the value of the last is returned as result. Otherwise the processing will fail fast and bypass all remainig mappings to the last statement orElse and return it's value. This is false according to your code.
You could use the map method:
private boolean isSequenceSuccessful() {
Optional<byte[]> result = doSomething().map(this::doAnotherThing)
.map(this::doSomethingElse);
if (result.isPresent()) return doMoreStuff(result.get());
else return false;
}
Look at the template pattern which I sometimes refer to as the pizza pattern because it is analogous to making a pizza. (eg. createDough(), putIngredients(), bake(), package(), deliver()). This might apply to your case. There are several examples and implementations out there but pick and choose which applies best to you. In your example above, I would create an abstract class and create concrete classes/implementations. Example to give you an idea:
public abstract class SequenceChecker {
// ...
public boolean isSequenceSuccessful() {
Optional<byte[]> result1 = doSomething();
Optional<byte[]> result2 = doAnotherThing(result1);
Optional<byte[]> result3 = doSomethingElse(result2);
return doMoreStuff(result3);
}
protected abstract boolean doMoreStuff(Optional<byte[]> result);
protected abstract Optional<byte[]> doSomethingElse(Optional<byte[]> result);
protected abstract Optional<byte[]> doAnotherThing(Optional<byte[]> result);
protected abstract Optional<byte[]> doSomething();
// ...
}
Use Optional::flatMap.
private boolean isSequenceSuccessful() {
Optional<Boolean> result = doSomething()
.flatMap(this::doAnotherThing)
.flatMap(this::doSomethingElse)
.map(this::doMoreStuff);
return result.isPresent() ? result.get() : false;
}
Is there a prettier way of doing the following in Java 8, avoiding isPresent and get?
void doStuff(String someValue, Optional<Boolean> doIt) {
if (doIt.isPresent()) {
if (doIt.get()) {
trueMethod(someValue);
} else {
falseMethod(someValue);
}
}
}
I tried using map, without success. But I probably didn't try hard enough?
You can use ifPresent instead of isPresent and get :
void doStuff(String someValue, Optional<Boolean> doIt) {
doIt.ifPresent (b -> {
if (b)
trueMethod(someValue);
else
falseMethod(someValue);
});
}
EDIT: fixed my code, since you can't use the ternary operator if trueMethod and falseMethod don't return anything.
This would be the functional approach using map:
Function<Boolean, Void> logic = isTrue -> {
if (isTrue) trueMethod(someValue);
else falseMethod(someValue);
return null;
};
doIt.map(logic);
However, it is really ugly, mostly because of your "not-very-functional" trueMethod/falseMethod, which both return void (leading to the ugly return null).