4

Given the code:

  Optional<String> myOptional = getMyOptional();
  myOptional.ifPresentOrElse(
      s -> Optional.ofNullable(someMap.get(s))
      .ifPresentOrElse(g -> {
            doSomeStuff(); 
          },
          () -> doErrHandling()),
      () -> doErrHandling());

Now I am thinking about how to simplify the chain and remove the duplicate code line (() -> doErrHandling()).

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
DerBenniAusA
  • 727
  • 1
  • 7
  • 13
  • 1
    Looks simple unless you want to use `g` in your actual code as `if (myOptional.isPresent() && someMap.containsKey(myOptional.get())) { doSomeStuff(); } else { doErrHandling(); }` – Naman Jul 16 '19 at 12:06

1 Answers1

9

Use map:

Optional<String> myOptional = getMyOptional() ;
myOptional.map(s -> someMap.get(s))
          .ifPresentOrElse(g -> doSomeStuff(), () -> doErrHandling());

map will return an Optional.empty() if the original Optional is empty, and will wrap the result of someMap.get(s) with an Optional otherwise.

Eran
  • 387,369
  • 54
  • 702
  • 768