英文:
Filter a Bean from List of List of Beans with exceptions handled in Java 8
问题
我想提取相应用户的一篇帖子。方法将以userId和postId作为输入。如何将以下逻辑转换为Java 8?
public Post findOnePost(int userId, int postId) {
Optional<User> userOptional = users.stream()
.filter(user -> user.getId() == userId)
.findFirst();
return userOptional.map(user ->
user.getUserPosts().stream()
.filter(post -> post.getId() == postId)
.findFirst()
.orElseThrow(() -> new PostNotFoundException("postId - " + postId)))
.orElseThrow(() -> new UserNotFoundException("userId - " + userId));
}
请确保在代码中导入所需的类和处理异常的方式。
英文:
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;
}
答案1
得分: 1
如果您想在用户不存在时引发UserNotFoundException异常,但在用户不包含所需帖子时返回null:
List<User> foundUsers = users.stream()
.filter(user -> Objects.equals(user.getId(), userId))
.collect(Collectors.toList());
if (foundUsers.isEmpty()) {
throw new UserNotFoundException("userId- " + userId);
}
return foundUsers.stream()
.map(User::getUserPosts)
.flatMap(List::stream)
.filter(post -> Objects.equals(post.getId(), postId))
.findFirst()
.orElse(null);
否则,可以简化为单一流:
public Optional<Post> findOnePost(int userId, int postId) {
return users.stream()
.filter(user -> Objects.equals(user.getId(), userId)) // 找到用户
.flatMap(user -> user.getUserPosts().stream()) // 提取帖子
.filter(post -> Objects.equals(post.getId(), postId)) // 过滤帖子
.findFirst(); // 找到第一个匹配的帖子
}
返回Optional而不是null或异常。使用此方法的类将决定是否引发异常。其次,返回null值可能会引发问题。使用Objects.equals(a, b)
将检查null值,以防止NPE。
英文:
If you want to throw UserNotFoundException, when user does not exist, but return null, when user is not containing desired post:
List<User> foundUsers = users.stream()
.filter(user -> Objects.equals(user.getId(), userId));
.collect(toList());
if(foundUsers.isEmpty()){
throw new UserNotFoundException("userId- " + userId);
}
return foundUsers.stream().map(User::getUserPosts)
.flatMap(List::stream)
.filter(post-> Objects.equals(user.getId(), userId))
.findFirst().orElse(null);
Otherwise it can be simplified to single stream:
public Optional<Post> findOnePost(int userId, int postId) {
return users.stream()
.filter(user -> Objects.equals(user.getId(), userId)) // find user
.flatMap(user-> user.getUserPosts().stream()) // extract posts
.filter(post-> Objects.equals(post.getId(), postId)) //filter posts
.findFirst(); // find first matching
}
Return Optional instead of null or an Exception. Class using this method will decide, to throw an exception or not. Secondly it's harmful to return null value, this may cause problems.
Using Objects.equals(a,b)
will check for null values, preventing NPE
答案2
得分: 1
I'll provide the translated code section:
尽管先前的答案已被接受,但由于您要求条件if (!isUserFound) {throw new UserNotFoundException("userId- " + userId);}
,我会提供我的答案。我认为,变量isUserFound
和异常UserNotFoundException
是误导的,因为您希望在找不到匹配的用户和帖子时抛出异常。
public Post findOnePost(int userId, int postId) throws UserNotFoundException {
return users.stream()
.filter(user -> Objects.equals(user.getId(), userId))
.flatMap(user -> user.getUserPosts().stream())
.filter(post -> Objects.equals(post.getId(), postId))
.findFirst()
.orElseThrow(() -> new UserNotFoundException("userId- " + userId));
}
我假设UserNotFoundException
是已检查异常,如果不是,请从方法声明中删除。
英文:
Even though earlier answer is accepted, I'll provide mine as you added have asked for condition if (!isUserFound) {throw new UserNotFoundException("userId- " + userId);}
. I think, variable isUserFound
and exception UserNotFoundException
is misleading because what you want is to throw exception when no matching user and post is found.
public Post findOnePost(int userId, int postId) throws UserNotFoundException {
return users.stream()
.filter(user -> Objects.equals(user.getId(), userId))
.flatMap(user -> user.getUserPosts().stream())
.filter(post -> Objects.equals(post.getId(), postId))
.findFirst()
.orElseThrow(() -> new UserNotFoundException("userId- " + userId));
}
I'm assuming UserNotFoundException
is checked exception, if not remove from method declaration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论