如何在Java 8中处理异常并从Bean的列表中过滤出一个Bean?

huangapple go评论42阅读模式
英文:

How to Filter a Bean from List of List of Beans with exceptions handled in Java 8?

问题

我有两个Bean类:User和Post。

User有以下成员:

private Integer id;
private String name;
private Date birthDate;
private List<Post> userPosts;

Post有以下成员:

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

任何帮助都将不胜感激。

英文:

I have a two Bean Classes : User and Post.

User have the following members:

private Integer id;
private String name;
private Date birthDate;
private List&lt;Post&gt; userPosts;

Post have the following members:

private Integer id;
private String title;
private Date postDate;

I want to extract one post for a corresponding user.
The methods will have the userId and postId as input.
How can I convert the following logic in 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(&quot;userId- &quot; + userId);
	}
	return null;
}

Any help will be highly appreciated.

答案1

得分: 1

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

You can use something like this, it returns Optional.

英文:
   users
            .stream()
            .findFirst(user -&gt; user.getId().equals(userId))
            .orElseThrow(new PostNotFoundException(&quot;userId- &quot; + userId))
            .flatMap(user -&gt; user.getPosts().stream())
            .findFirst(post -&gt; post.getId() == postId)

You can use something like this, it returns Optional

huangapple
  • 本文由 发表于 2020年8月13日 16:46:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63391418.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定