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

JavaJava 8Optional

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

With Apache Commons:

.filter(StringUtils::isNotEmpty)

Solution 3 - Java

Java 11 answer:

var optionalString = Optional.ofNullable(str).filter(Predicate.not(String::isBlank));

String::isBlank deals with a broader range of 'empty' characters.

Solution 4 - Java

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.

Solution 5 - Java

You can use map :

String ppo="";
Optional<String> ostr = Optional.ofNullable(ppo)
                                .map(s -> s.isEmpty()?null:s);
System.out.println(ostr.isPresent()); // prints false

Solution 6 - Java

If you use Guava, you can just do:

Optional<String> ostr = Optional.ofNullable(Strings.emptyToNull(ppo));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGerm&#225;n BouzasView Question on Stackoverflow
Solution 1 - JavaassyliasView Answer on Stackoverflow
Solution 2 - JavaFeecoView Answer on Stackoverflow
Solution 3 - JavaMichael BarnwellView Answer on Stackoverflow
Solution 4 - JavaJon SkeetView Answer on Stackoverflow
Solution 5 - JavaEranView Answer on Stackoverflow
Solution 6 - JavaGonzalo Vallejos BobadillaView Answer on Stackoverflow