Search code examples
javaoption-type

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?


Solution

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

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