Understanding the optional <T> .map ()

Considering an example of using Optional , where the option is first loaded by invoking the database and then mapped to the Spring security UserDetails instance. The code is as follows:

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

On the last line, this will be equal to return new CustomUserDetails(user.get()) .

Also, does anyone know if there is an even shorter, more fluid way to write the above example?

+5
source share
1 answer

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

This avoids the useless variable, isolates the exception at the end, and avoids the unpleasant call to get() , which is guaranteed to work fine here, because you used to call orElseThrow() before.

+10
source

Source: https://habr.com/ru/post/1273747/


All Articles