Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 756
Germán Bouzas Avatar asked Feb 04 '15 13:02

Germán Bouzas


People also ask

What is the use of optional empty () in Java?

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.

How do you change a string from optional to string in Java?

Java 8 – Convert Optional<String> to String In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .

Does optional ofNullable check empty 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.


2 Answers

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.

like image 88
assylias Avatar answered Sep 22 '22 04:09

assylias


With Apache Commons:

.filter(StringUtils::isNotEmpty) 
like image 21
Feeco Avatar answered Sep 25 '22 04:09

Feeco