I'm starting with this code:
String startingValue = getMyValue();
String finishingValue = "";
if (startingValue != null) {
finishingValue = startingValue;
} else {
System.out.println("Value was null");
}
I want to transform it using Java 8 options to something like this:
Optional startingOptional = getMyOptional();
String finishingValue =
startingOptional
.map(value -> value)
.orElse(System.out.println("value not found"));
My question is: Is there a way to combine Java8 Optional returning a value with printing a message on null?
解决方案
Use orElseGet:
Optional startingOptional = getMyOptional();
String finishingValue = startingOptional.orElseGet(() -> {
System.out.println("value not found");
return "";
});
Using .map(value -> value) is useless: transforming a value into itself doesn't change anything.