Filter a Bean from List of List of Beans with exceptions handled in Java 8.

huangapple go评论63阅读模式
英文:

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&lt;Post&gt; 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(&quot;userId- &quot; + 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&lt;User&gt; foundUsers = users.stream()
.filter(user -&gt; Objects.equals(user.getId(), userId));
.collect(toList());
if(foundUsers.isEmpty()){
 throw new UserNotFoundException(&quot;userId- &quot; + userId);
}
return foundUsers.stream().map(User::getUserPosts)
.flatMap(List::stream)
.filter(post-&gt; Objects.equals(user.getId(), userId))
.findFirst().orElse(null);

Otherwise it can be simplified to single stream:

public Optional&lt;Post&gt; findOnePost(int userId, int postId) {
    return users.stream()
      .filter(user -&gt; Objects.equals(user.getId(), userId)) // find user
      .flatMap(user-&gt; user.getUserPosts().stream()) // extract posts
      .filter(post-&gt; 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(&quot;userId- &quot; + 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 -&gt; Objects.equals(user.getId(), userId))
        .flatMap(user -&gt; user.getUserPosts().stream())
        .filter(post -&gt; Objects.equals(post.getId(), postId))
        .findFirst()
        .orElseThrow(() -&gt; new UserNotFoundException(&quot;userId- &quot; + userId));
  }

I'm assuming UserNotFoundExceptionis checked exception, if not remove from method declaration.

huangapple
  • 本文由 发表于 2020年8月13日 17:24:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63392038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定