2

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
j.dev
  • 41
  • 2

2 Answers2

3

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.

2

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);
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • Changing the signature of the method to be invoked to start returning a value while it was void, doesn't make much sense imho. – Naman Mar 12 '20 at 04:08