Understanding Optional<T>.map()

Ole :

Reviewing an example use of Optional where the optional is first loaded with a database call and then mapped to a Spring security UserDetails instance. The code looks like this:

Optional<User> user = userRepository.findByName(username);
user.orElseThrow(()-> new UsernameNotFoundException("Ahhh Shuckkkks!!!");
return user.map(CustomUserDetails::new).get();

In the last line would that call equal return new CustomUserDetails(user.get()).

Also anyone know if there's an even shorter more fluid way to write the above example?

JB Nizet :

Yes, that would be equivalent. But the code should rather be written as

return userRepository.findByName(username)
    .map(CustomUserDetails::new)
    .orElseThrow(()-> new UsernameNotFoundException("Ahhh Shuckkkks!!!"));

That avoids a useless variable, isolates the exceptional case at the end, and avoids the nasty call to get(), which is only guaranteed to work fine here because you have called orElseThrow() before.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475748&siteId=1