如何从Java8中处理异常的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

最新更新