问题
I am trying to find the most concise (and meaningful) way of using Java Optional
, to read the first value off a Optional<String>
and return the String if exists, or return "NOT_FOUND". Here is the code I am working with:
public static String getValue(Optional<String> input) {
return input.ifPresent(val -> val.get()).orElse("NOT_FOUND")
}
The methods of Optional apparently have very specific purposes but the API has left me confused.
Update (4/13/2018):
The code in my question is incorrect, because if I regarded val
as the value inside the Optional, then val.get()
does not make any sense. Thanks for pointing that out, @rgettman.
Also, I added another part to my question in the accepted answer's comments, i.e. I needed a way to manipulate the String value, if present, before returning. The orElse("NOT_FOUND")
is still applicable, if the Optional does not contain a value. So what is an acceptable use of the Optional
API to achieve the following?
public static String getValue(Optional<String> input) {
return input.isPresent() ? input.get().substring(0,7).toUpperCase() : "NOT_FOUND";
}
@Aominè's answer and follow up comments addressed both parts of this question.
回答1:
All you have to do is change your return statement to:
return input.orElse("NOT_FOUND");
This will return the object in the Optional if present else returns "NOT_FOUND".
That said, I'd avoid using Optional's as parameters. see here.
回答2:
If you need to manipulate the string value, if it is present before returning it, use map
method:
public static String getValue(Optional<String> input) {
return input.map(s -> s.substring(0,7).toUpperCase()).orElse("NOT_FOUND");
}
If input
is empty the method returns default value - "NOT_FOUND"
, otherwise capitalized part of the string is returned.
getValue(Optional.ofNullable(null));
$6 ==> "NOT_FOUND"
getValue(Optional.of("some long string"));
$7 ==> "SOME LO"
来源:https://stackoverflow.com/questions/49807204/conditional-extract-of-value-from-java-optional