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 = \"\";
Opt
With Apache Commons:
.filter(StringUtils::isNotEmpty)
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.
If you use Guava, you can just do:
Optional<String> ostr = Optional.ofNullable(Strings.emptyToNull(ppo));
Java 11 answer:
var optionalString = Optional.ofNullable(str).filter(Predicate.not(String::isBlank));
String::isBlank
deals with a broader range of 'empty' characters.
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.
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