问题描述
我有两个Bean类:User和Post。
用户具有以下成员:
private Integer id;
private String name;
private Date birthDate;
private List<Post> userPosts;
帖子具有以下成员:
private Integer id;
private String title;
private Date postDate;
我想为相应的用户提取一篇帖子。 这些方法将以userId和postId作为输入。 如何在Java 8中转换以下逻辑?
public Post findOnePost(int userId,int postId) {
boolean isUserFound = false;
for (User user : users) {
if (user.getId() == userId) {
isUserFound = true;
for (Post post : user.getUserPosts()) {
if (post.getId() == postId) {
return post;
}
}
}
}
if (!isUserFound) {
throw new UserNotFoundException("userId- " + userId);
}
return null;
}
解决方法
如果要抛出UserNotFoundException,则当用户不存在时,但如果用户不包含所需的帖子,则返回null:
List<User> foundUsers = users.stream()
.filter(user -> Objects.equals(user.getId(),userId));
.collect(toList());
if(foundUsers.isEmpty()){
throw new UserNotFoundException("userId- " + userId);
}
return foundUsers.stream().map(User::getUserPosts)
.flatMap(List::stream)
.filter(post-> Objects.equals(user.getId(),userId))
.findFirst().orElse(null);
否则,它可以简化为单个流:
public Optional<Post> findOnePost(int userId,int postId) {
return users.stream()
.filter(user -> Objects.equals(user.getId(),userId)) // find user
.flatMap(user-> user.getUserPosts().stream()) // extract posts
.filter(post-> Objects.equals(post.getId(),postId)) //filter posts
.findFirst(); // find first matching
}
返回Optional而不是null或Exception。使用此方法的类将决定是否引发异常。其次,返回null值很有害,这可能会导致问题。
使用Objects.equals(a,b)
将检查是否存在空值,从而防止NPE
即使接受了较早的答案,我也会提供您所要求的条件if (!isUserFound) {throw new UserNotFoundException("userId- " + userId);}
的信息。我认为,变量isUserFound
和异常UserNotFoundException
会产生误导,因为您想要的是在找不到匹配的用户和帖子时引发异常。
public Post findOnePost(int userId,int postId) throws UserNotFoundException {
return users.stream()
.filter(user -> Objects.equals(user.getId(),userId))
.flatMap(user -> user.getUserPosts().stream())
.filter(post -> Objects.equals(post.getId(),postId))
.findFirst()
.orElseThrow(() -> new UserNotFoundException("userId- " + userId));
}
我假设UserNotFoundException
被检查为异常,如果未从方法声明中删除。