简体   繁体   中英

How can I return a value while checking if a Java 8 Optional is present?

How can I return a value but make sure checking .get() is valid?

Assume date is an Optional<String> .

methodThatTakesStringParam(date.ifPresent(s->s.get().replace("-", ""))) );  

If I just use this and .get is performed it throws if its not present!

methodThatTakesStringParam( date.get().replace("-", "") );  

How do I handle this? All the examples I see are something like

date.ifPresent(System.out.println("showing that you can print to io is useless to me =)") 

but I want to return a string in this case -- the empty string if .ifPresent() is false.

It sounds like what you want is:

methodThatTakesStringParam(date.map(s->s.replace("-", ""))).orElse(""));

(See the Javadoc for Optional<U>.map(Function<? super T,? extends U>) . date.map(s->s.replace("-", "")) is roughly equivalent to date.isPresent() ? Optional.of(date.get().replace("-", "")) : Optional.empty() .)


Edited to add: That said, in this specific case, it might be simpler to write:

methodThatTakesStringParam(date.orElse("").replace("-",""));

since "".replace("-","") gives "" anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM