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?
The method Optional. map(Function) applies the given function to the optional value if it is present and returns an optional with the result or empty optional.
The filter() method of java. util. Optional class in Java is used to filter the value of this Optional instance by matching it with the given Predicate, and then return the filtered Optional instance. If there is no value present in this Optional instance, then this method returns an empty Optional instance.
public final class Optional<T> extends Object. A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With