In Java 8, transform Optional<String> of an empty String in Optional.empty
JavaJava 8OptionalJava Problem Overview
Given a String I need to get an Optional
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));