Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Optional<T>.map()

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?

like image 968
Ole Avatar asked Nov 29 '17 16:11

Ole


People also ask

What does map do in optional?

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.

What does the optional filter () method do?

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.

What is optional T in Java?

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.

What is the use of optional ()?

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.


1 Answers

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.

like image 148
JB Nizet Avatar answered Oct 12 '22 23:10

JB Nizet