How to use Java Optional to elegantly replace Ternary operators

  • A+

A super simple question:

Here's my plain Java code using traditional ternary operator ?

public DateTime getCreatedAt() {     return !recordA.isPresent() ? recordB.get().getCreatedAt() : recordA.get().getCreatedAt(); } 

My best bet is following:

public DateTime getCreatedAt() {     return         record -> record.getCreatedAt())         .orElse(recordB.get().getCreatedAt());   } 

This could compile, but looks like it's not behaving correctly. It always executes both branches, i.g. when recordA isPresent(), it still executes recordB.get().getCreatedAt() which throws me

java.util.NoSuchElementException: No value present 

Any is appreciated! Basically, I'd like to replace the traditional ternary option with more advanced Optional/lamda features. THANKS!


To avoid eagerly evaluating else-branches, use orElseGet, which takes an instance of the functional interface Supplier:

return     record -> record.getCreatedAt())     .orElseGet(() -> recordB.get().getCreatedAt()); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: