Given a String I need to get an Optional, whereby if the String is null or empty the result would be Optional.empty. I can do it this way:
String ppo = "";
Optional<String> ostr = Optional.ofNullable(ppo);
if (ostr.isPresent() && ostr.get().isEmpty()) {
ostr = Optional.empty();
}
But surely there must be a more elegant way.
How about:
Optional<String> ostr = ppo == null || ppo.isEmpty()
? Optional.empty()
: Optional.of(ppo);
You can put that in a utility method if you need it often, of course. I see no benefit in creating an Optional
with an empty string, only to then ignore it.
See more on this question at Stackoverflow