I am using Java-8 's flatMap operation to make a part of my code smaller.
I know that if my code is as follows:
if (giftOptional.isPresent()) {
Gift gift = giftOptional.get();
Optional<Boolean> giftIsWrapped = gift.isWrapped();
return giftIsWrapped.isPresent() && giftIsWrapped.get();
}
return false;
then it can be changed to:
return giftOptional.flatMap(Gift::isWrapped)
.orElse(Boolean.FALSE);
but what if the isWrapped method does not return an Optional? That is, if the code is like this:
if (giftOptional.isPresent()) {
Gift gift = giftOptional.get();
boolean giftIsWrapped = gift.isWrapped();
return giftIsWrapped;
}
return false;
then can the same code apply? That is:
return giftOptional.flatMap(Gift::isWrapped)
.orElse(Boolean.FALSE);
Also, what if I need to add some argument to the function? For example, the code is:
if (giftOptional.isPresent()) {
String gift = giftOptional.get();
boolean giftIsWrapped = gift.equals("some string");
return giftIsWrapped;
}
return false;
what should be the corresponding code using flatMap in that case?