How to replace "return optObj.isPresent() ? new Obj2(optObj) : null" in a functional style?

DIBits :

My IDE (InteliJ) keeps pointing me that my code "Can be replaced with single expression in functional style", highlighting the isPresent():

return timestamp.isPresent() ? new Obj2(timestamp.get()) : null;

timestamp is initialised like an Optional:

Optional<Date> timestamp = ...

My assumption is that I should use ifPresent. like this timestamp.ifPresent(Obj2::new). But ifPresent is void and I have no opportunity to return the created Object. Also cant then return null. Is there a solution to my code?

Ousmane D. :

You're correct in saying ifPresent returns void and hence not suitable in this case. Your IDE is suggesting that you can simply do:

timestamp.map(Obj2::new).orElse(null);

This reads as "if the Optional timestamp has a present state then pass the object it contains into the Obj2 constructor and returns this new Obj2 instance otherwise (orElse) return null.


on another note, IntelliJ IDEA can help you generate the code it's suggesting.

for example, given the below screenshot:

enter image description here

I simply clicked on the "highlighted" part and pressed "ALT + ENTER", and IntelliJ suggests whether it should replace the condition with a functional style.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130642&siteId=1