You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java 8 Streams筛选评论数最多的newsId记录

基于Java Stream实现评论量最高newsId统计的方案

思路纠偏

尝试实现Predicate做过滤的方向不匹配需求:Predicate仅用于按条件筛除流中不符合规则的元素,而当前需求是统计所有新闻的评论数、找出评论量最高的newsId,属于分组聚合计算场景,不需要走过滤逻辑。

实现逻辑

  • 第一步:对新闻列表按newsId分组,统计每个id对应的评论条数(单条News对象对应一条评论,分组计数结果即为对应新闻的评论总量)
  • 第二步:遍历分组得到的「newsId-评论数」键值对,取评论数最大的条目,对应的key就是目标结果

完整可运行代码

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class News {
    int newsId;
    String postByUser;
    String commentByUser;
    String comment;

    public News(int newsId, String postByUser, String commentByUser, String comment) {
        this.newsId = newsId;
        this.postByUser = postByUser;
        this.commentByUser = commentByUser;
        this.comment = comment;
    }

    public int getNewsId() {
        return newsId;
    }

    public void setNewsId(int newsId) {
        this.newsId = newsId;
    }

    public String getPostByUser() {
        return postByUser;
    }

    public void setPostByUser(String postByUser) {
        this.postByUser = postByUser;
    }

    public String getCommentByUser() {
        return commentByUser;
    }

    public void setCommentByUser(String commentByUser) {
        this.commentByUser = commentByUser;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }
}

class Main {

    static List<News> news = Arrays.asList(
        new News(1, "fb_Userpost", "fb_Usercomment", "comment1"),
        new News(2, "insta_userpost", "insta_usercomment", "comment2"),
        new News(1, "whatsapp_userpost", "whatsapp_usercomment", "comment3"),
        new News(1, "whatsapp_userpost", "whatsapp_usercomment", "comment3"),
        new News(3, "whatsapp_userpost", "whatsapp_usercomment", "comment3")
    );
    public static void main(String args[]) {
        // 分组统计每个newsId的评论数
        Map<Integer, Long> newsCommentCountMap = news.stream()
                .collect(Collectors.groupingBy(News::getNewsId, Collectors.counting()));
        
        // 取评论数最高的newsId
        Integer topNewsId = newsCommentCountMap.entrySet()
                .stream()
                .max(Map.Entry.comparingByValue())
                .get()
                .getKey();
        
        System.out.println("评论数量最多的newsId为:" + topNewsId);
    }
}

运行结果

基于提供的测试数据,newsId为1的新闻共有3条评论,为所有新闻最高,运行后输出如下:

评论数量最多的newsId为:1

如果存在多个newsId评论数并列最高的场景,可以调整逻辑把所有并列最高的id收集为列表,只需要把取max的逻辑替换为按最高值过滤收集即可。

内容的提问来源于stack exchange,提问作者Yash Tumu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 21:18:15