Java Stream Optional: How can I convert the multiple inner Optional present condition to Optional.flatMap()

57 Views Asked by At

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

1

There are 1 best solutions below

0
Emanuel Trandafir On

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);