parrotjack
parrotjack

Reputation: 512

Java Stream to Collect Entity

I have a method which return User entity,

am trying to map them and collect it to Spring Core API, UserDetails.

User user = userRepository.findByName(userName);
       Optional.ofNullable(user)
                .map(a -> new org.springframework.security.core.userdetails.User(a.getName(),
                        a.getPassword(), new ArrayList<>())).stream()
                .collect(Collectors.toList())

The above returns List<UserDetails>but in my case, i want to collect it UserDetails entity (1 item) and findByName() may return NULL, in this case i need to throw custom exception.

is there any way to handle this situation?

Upvotes: 1

Views: 763

Answers (2)

JB Nizet
JB Nizet

Reputation: 691635

if is your friend.

User user = userRepository.findByName(userName);
org.springframework.security.core.userdetails.User springUser = null;
if (user != null) {
    springUser = new org.springframework.security.core.userdetails.User(user.getName(),
                        user.getPassword(), new ArrayList<>());
}

Note that your repo shouldn't return null. It should return an Optional. That's what Optional is for: to signal that a method can return an absent value. Don't abuse Optional to replace null checks. If it returns an Optional, then you can use

springUser = optionalUser.map(...).orElse(null);

Upvotes: 1

ernest_k
ernest_k

Reputation: 45309

You're unnecessarily converting your optional to a stream. All you need to do is read the value from the optional:

org.springframework.security.core.userdetails.User userDetails = 
    Optional.ofNullable(user)
      .map(a -> new org.springframework.security.core.userdetails.User(a.getName(),
                        a.getPassword(), new ArrayList<>()))
      .orElse(null); //null returned if optional is empty.

Upvotes: 3

Related Questions