In Java 8, transform Optional<String> of an empty String in Optional.empty
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.
You could use a filter:
Optional<String> ostr = Optional.ofNullable(ppo).filter(s -> !s.isEmpty());
That will return an empty Optional if ppo
is null or empty.
With Apache Commons:
.filter(StringUtils::isNotEmpty)