如何用Java 8中处理的异常从Bean列表中过滤Bean? [英] How to Filter a Bean from List of List of Beans with exceptions handled in Java 8?
本文介绍了如何用Java 8中处理的异常从Bean列表中过滤Bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个Bean类:User和Post.
I have a two Bean Classes : User and 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中转换以下逻辑?
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("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
You can use something like this, it returns Optional
这篇关于如何用Java 8中处理的异常从Bean列表中过滤Bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文