Confirming whether a user is registered, using Optional class in Java 8 I start to learn Java 8 and I wondering is that kind of using Optional class is correct?

@Override
public Response confirmRegister(Request request) {
    return mailTokenRepository.findByToken(request.getToken()).map(mailToken -&gt; {
        if (mailToken.getTypeToken().equals(TypeToken.REGISTER)
                &amp;&amp; mailToken.getToken().equals(request.getToken())) {
            return Optional.ofNullable(userRepository.findOne(mailToken.getUser().getId())).map(user -&gt; {
                user.setBlock(false);
                userRepository.save(user);
                mailTokenRepository.delete(mailToken);
                return jsonService.prepareResponseForUser(StatusMessage.SUCCESS, "SUCCESS_REGISTERED", null, null,
                        true);
            }).orElseGet(() -&gt; jsonService.prepareErrorResponse("INCORRECT_DATA"));
        } else
            return jsonService.prepareErrorResponse("INCORRECT_DATA");
    }).orElseGet(() -&gt; jsonService.prepareErrorResponse("INCORRECT_DATA"));

}
Concerning your question about the usage of Optional: yes, this usage is correct and it roughly respects the principles of functional programming.

However, I would recommend a few changes to increase the readability of this piece of code:

1) jsonService.prepareErrorResponse("INCORRECT_DATA") appears three times: it needs to be extracted into a dedicated method.

2) The main valid return case starting with return Optional.ofNullable should also be extracted into a dedicated method.

3) The condition should also be extracted.

After this refactoring, the code will resemble something like

public Response confirmRegister2(Request request) {
  return mailTokenRepository.findByToken(request.getToken())
                            .map(mailToken -&gt; {
    if (isTokenValid(mailToken, request)) {
      return responseForUser(mailToken).orElseGet(this::errorResponse);
    } else {
      return this.errorResponse();
    }
  }).orElseGet(this::errorResponse);
}

private boolean isTokenValid(MailToken mailToken, Request request) {
  return mailToken.getTypeToken().equals(TypeToken.REGISTER)
         &amp;&amp; mailToken.getToken().equals(request.getToken());
}

private Response errorResponse() {
  return jsonService.prepareErrorResponse("INCORRECT_DATA");
}

private Optional&lt;Response&gt; responseForUser(MailToken mailToken) {
  return Optional.ofNullable(userRepository.findOne(mailToken.getUser().getId()))
                .map(user -&gt; {
                      user.setBlock(false);
                      userRepository.save(user);
                      mailTokenRepository.delete(mailToken);
                      return jsonService.prepareResponseForUser(StatusMessage.SUCCESS,
                                                              "SUCCESS_REGISTERED", null, null, true);
                    });
}


... which is definitely more readable and easier to understand. :)