How to use Java Optional to elegantly replace Ternary operators

1827 views java
-1

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, 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!

answered question

.orElseGet(() -> recordB.get().getCreatedAt()); ?

You need orElseGet. You can also use two optionals and or().

Is recordB Optional too?

1 Answer

13

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

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

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories