如何用Java 8中处理的异常从Bean列表中过滤Bean?

问题描述

我有两个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;
}

我们将不胜感激任何帮助。

解决方法

   users
            .stream()
            .findFirst(user -> user.getId().equals(userId))
            .orElseThrow(new PostNotFoundException("userId- " + userId))
            .flatMap(user -> user.getPosts().stream())
            .findFirst(post -> post.getId() == postId)

您可以使用类似的方法,它返回Optional