java - 如何从 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;
}
任何帮助将不胜感激。
解决方案
users
.stream()
.findFirst(user -> user.getId().equals(userId))
.orElseThrow(new PostNotFoundException("userId- " + userId))
.flatMap(user -> user.getPosts().stream())
.findFirst(post -> post.getId() == postId)
你可以使用这样的东西,它会返回Optional
推荐阅读
- r - R中的calc()函数错误
- python-3.x - N 未定义(全球存在)
- jess - Jess在例行调用中报错
- opengl - OpenGL为什么在相同数量的片段上重复纹理可能会降低性能?
- node.js - 如何解决Nodejs中的“错误:ENOENT:没有这样的文件或目录”
- java - What is an illegal reflective access?
- azure - 在 Azure API 管理中向特定终结点添加授权
- c# - 模型上的实体框架在构造函数中创建传递参数
- publish - 谷歌地图街景发布
- katalon-studio - 如何在 Katalon 工作室处理日期选择器?