英文:
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<Post> 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("userId- " + 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 -> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论