问题
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<String> 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?
回答1:
Use orElseGet:
Optional<String> 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.
回答2:
If you are using Java 9 or later and you don't want to use default stub for empty value but instead handle empty and non-empty cases separately, you can also use Optional#ifPresentOrElse(Consumer, Runnable) method whose second argument is the handler for empty value.
For your case it would look like:
Optional<String> startingOptional = getMyOptional();
finishingValue =
startingOptional
.map(value -> value)
.ifPresentOrElse(
value -> {/* do something with your value */},
() -> System.out.println("value not found")
);
or, ommiting the local variable:
getMyOptional()
.map(value -> value)
.ifPresentOrElse(
value -> {/* do something with your value */},
() -> System.out.println("value not found")
);
来源:https://stackoverflow.com/questions/59517743/is-there-a-way-to-combine-java8-optional-returning-a-value-with-printing-a-messa