收集实体的Java流

问题描述 投票:0回答:2

我有一个返回用户实体的方法,

试图映射它们并将其收集到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())

以上返回List<UserDetails>,但在我的情况下,我想收集它UserDetails实体(1个项目,并且findByName()可能返回NULL,在这种情况下,我需要抛出自定义异常。

有什么方法可以处理这种情况?

java java-8 java-stream optional
2个回答
2
投票

您不必要将可选内容转换为流。您需要做的就是从可选的值中读取值:

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.

1
投票

if是你的朋友。

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<>());
}

请注意,您的存储库不应返回null。它应该返回一个可选的。这就是Optional的目的:表示方法可以返回缺少的值。不要滥用可选来替换空检查。如果返回可选,则可以使用

springUser = optionalUser.map(...).orElse(null);
© www.soinside.com 2019 - 2024. All rights reserved.