【问题标题】:How to filter stream values using Map of Lists?如何使用列表映射过滤流值?
【发布时间】:2019-07-05 22:01:25
【问题描述】:

我有一个实体列表,我需要使用过滤器和 Map 以及必要的键和值来删除其中的一些。

看起来是这样的。有List<Comment> commentsListMap<Integer, List<Post>> postsById。评论实体有方法getByPostId。地图看起来像<Post id, has amount of comments>。 我需要从 commentsList cmets 中删除与 Post 相关且少于 3 cmets 的 cmets。 我试着这样做:

Stream<E> ofAtLeastComments(Stream<E> comments, Stream<Post> posts, Integer count) {
    Map<Integer, List<Post>> postById = posts
            .collect(Collectors.groupingBy(Post::getId)
            );
    return comments
            .filter(comment -> postById.get(comment.getCommentId()).size() >= count);
}

但它返回零值。

【问题讨论】:

  • 您的地图键是帖子 ID,而不是评论 ID。
  • 你的问题很混乱,没有提供足够的信息来说明你想要做什么。
  • @Alexey,请✓ 回答或更新您的问题。

标签: java lambda java-stream


【解决方案1】:

正如 JB Nizet 指出的那样,代码似乎混淆了帖子 ID 和评论 ID:

Stream<E> ofAtLeastComments(Stream<E> comments, Stream<Post> posts, Integer count) {
    Map<Integer, List<Post>> posts = posts.collect(Collectors.groupingBy(Post::getId));
    return comments.filter(comment -> posts.get(comment.getPostId()).size() >= count);
    //                                                     ^^^^
}

但是方法名听起来更像你想要的:

<E extends Comment> Stream<Post> ofAtLeastComments(Stream<E> comments, Stream<Post> posts, Integer count) {
    // Number of comments per post ID 
    Map<Integer, Long> commentCounts = comments
            .collect(Collectors.groupingBy(Comment::getPostId, Collectors.counting()));
    return posts.filter(post -> commentCounts.getOrDefault(post.getId(), 0L) >= count);
}

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2018-08-22
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    相关资源
    最近更新 更多