How to use Java Optional without if condition to add different logic

Viewed 100

I want to apply different logic to Optional value like below

Optional<String> alarm = getAlarm();
if (alarm.isPresent()) {
    testAutoStopAndRollback(alarm.get());
} else {
    testWithoutAutoStopAndRollback();
}

Is there a more concise way to implement the same logic? I know I can move half of the logic to ifPresent()

alarm.ifPresent(name -> testAutoStopAndRollback(name));

How can I do the rest part?

To clarify the question, my code is stick to Java 8 so I won't be able to use ifPresentOrElse in Java 9.

2 Answers

I feel like your first example is fine already. Unless you can upgrade to Java 9, Optional does not contain a method like ifPresentOrElse. Just stick to the first rule of programming: "If it works, don't touch it!" :)

If you want to create more classes to clean up your code a little, check out this question.

One way you can do it by returning some value from testAutoStopAndRollback and testWithoutAutoStopAndRollback, for example i would return boolean values to identify value is present or not

testAutoStopAndRollback(val) ---> returns true
testWithoutAutoStopAndRollback ---> returns false

And then using Optional

boolean value = alarm.map(this::testAutoStopAndRollback).orElseGet(this::testWithoutAutoStopAndRollback);
Related