Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify ifPresentOrElse chain

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()).

like image 659
DerBenniAusA Avatar asked Jan 26 '23 01:01

DerBenniAusA


1 Answers

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.

like image 189
Eran Avatar answered Jan 30 '23 05:01

Eran