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.