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.
Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value. Parameters: This method accepts nothing. Return value: This method returns an empty instance of this Optional class.
Java 8 – Convert Optional<String> to String In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .
Solution: Using Optional Class Optional. ofNullable() method of the Optional class, returns a Non-empty Optional if the given object has a value, otherwise it returns an empty Optional. We can check whether the returned Optional value is empty or non-empty using the isPresent() method.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With