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?
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:
I simply clicked on the "highlighted" part and pressed "ALT + ENTER", and IntelliJ suggests whether it should replace the condition with a functional style.