首页 > 解决方案 > 如何从 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;
}

任何帮助将不胜感激。

标签: javajava-8java-stream

解决方案


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

你可以使用这样的东西,它会返回Optional


推荐阅读