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 recordA.map(
record -> record.getCreatedAt())
.orElse(recordB.get().getCreatedAt());
}
This could compile, but looks like it's not behaving correctly.
It always executes both branches, for e.g. when recordA
isPresent(), it still executes recordB.get().getCreatedAt()
which throws me
java.util.NoSuchElementException: No value present
Any help is appreciated!
Basically, I'd like to replace the traditional ternary operator with more advanced Optional/lamda features.