简体   繁体   中英

How does Optional.map() exactly works?

According to javadoc , Optional.map() returns an Optional.

In the following snippet:

public String getName(Long tpUserId) {
    Optional<TpUser> selectedTpUser = tpUserRepo.findById(tpUserId);
    return selectedTpUser.map(user -> user.getFirstName() + " " + user.getSurName())
        .orElseThrow(() -> new IllegalArgumentException("No user found for this id"));
  }

it looks like, I want to return a String but I get an Optional. Nevertheless there is no compile error. Why?

You are totally correct. The map() method returns an Optional, and I applaud your use of the javadoc. The difference here is that you then invoke the orElseThrow() method on that Optional that map() returned. If you refer to the javadoc for orElseThrow() , you will see that it returns "the present value [of the Optional]". In this case, that is a String.

The whole chain of operations returns a String :

  • The first step ( map(...) ) maps the Optional<User> to an Optional<String> .
  • The second step ( orElseThrow(...) ) unwraps the Optional<String> , thus returning a String (or throwing an IllegalArgumentException , if empty).

You can find the source code of Optional::map here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM