In Java 8, transform Optional<String> of an empty String in Optional.empty

Germ&#225;n Bouzas picture Germán Bouzas · Feb 4, 2015 · Viewed 49.8k times · Source

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.

Answer

assylias picture assylias · Feb 4, 2015

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.