-1

I am trying to convert the multiple Optional isPresent to Optional.flatMap but not getting on how to do that.

private Optional<Commit> getCommit1 (String id, Integer number) {
    **Optional<Revision> revision = repository.findById(id,number);
    if (revision.isPresent()) {
        Optional<Commit> commit = commitRepository.findById(revision.get().getCommitId());
        if (commit.isPresent()) {
            return commit;
        }
    }
    return Optional.empty();**
}

I want convert the bold part into single Optional.flatMap Can someone help here

Naman
  • 27,789
  • 26
  • 218
  • 353
  • 3
    It seems, you are looking for a "one-liner"? Something like `return repository.findById(id,number).map(Revision::getCommitId).flatMap(commitRepository::findById)`? – Seelenvirtuose Apr 24 '23 at 15:10

1 Answers1

0

As you mentioned, you should yous e the flatMap method. One way to do it would be like this:

repository.findById(id,number)
    .map(revision -> revision.getCommitId())
    .flatMap(commitId -> commitRepository.findById(commitId));
    

Additionally, you can use method references for the map and flatMap parameters, resulting in a more concise code:

repository.findById(id,number)
    .map(Revision::getCommitId)
    .flatMap(commitRepository::findById);
Emanuel Trandafir
  • 1,526
  • 1
  • 5
  • 13