首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Java递归实现评论多级回复

Java递归实现评论多级回复

作者头像
用户10384376
发布2023-02-26 12:50:17
发布2023-02-26 12:50:17
1.7K0
举报
文章被收录于专栏:码出code码出code

最近工作需要做一个评论功能,除了展示评论之外,还需要展示评论回复,评论的回复的回复,这里就用到了递归实现评论的多级回复

评论实体

数据库存储字段:id 评论id、parent_id 回复评论id、message 消息。其中如果评论不是回复评论,parent_id-1

创建一个评论实体 Comment

代码语言:javascript
复制
public class Comment {

    /**
     * id
     */
    private Integer id;

    /**
     * 父类id
     */
    private Integer parentId;

    /**
     * 消息
     */
    private String message;
}

查询到所有的评论数据。方便展示树形数据,对Comment添加回复列表

List<ViewComment> children

ViewComment结构如下:

代码语言:javascript
复制
// 展示树形数据
public class ViewComment {

    /**
     * id
     */
    private Integer id;

    /**
     * 父类id
     */
    private Integer parentId;

    /**
     * 消息
     */
    private String message;

    /**
     * 回复列表
     */
    private List<ViewComment> children = new ArrayList<>();
}

添加非回复评论

非回复评论的parent_id-1,先找到非回复评论:

代码语言:javascript
复制
List<ViewComment> viewCommentList = new ArrayList<>();
// 添加模拟数据
Comment comment1 = new Comment(1,-1,"留言1");
Comment comment2 = new Comment(2,-1,"留言2");
Comment comment3 = new Comment(3,1,"留言3,回复留言1");
Comment comment4 = new Comment(4,1,"留言4,回复留言1");
Comment comment5 = new Comment(5,2,"留言5,回复留言2");
Comment comment6 = new Comment(6,3,"留言6,回复留言3");

//添加非回复评论
for (Comment comment : commentList) {
    if (comment.getParentId() == -1) {
        ViewComment viewComment = new ViewComment();
        BeanUtils.copyProperties(comment,viewComment);
        viewCommentList.add(viewComment);
    }
}

递归添加回复评论

遍历每条非回复评论,递归添加回复评论:

代码语言:javascript
复制
for(ViewComment viewComment : viewCommentList) {
    add(viewComment,commentList);
}


private void add(ViewComment rootViewComment, List<Comment> commentList) {
    for (Comment comment : commentList) {
        // 找到匹配的 parentId  
        if (rootViewComment.getId().equals(comment.getParentId())) {
            ViewComment viewComment = new ViewComment();
            BeanUtils.copyProperties(comment,viewComment);
            rootViewComment.getChildren().add(viewComment);
            //递归调用 
            add(viewComment,commentList);
        }
    }
}
  • 遍历每条非回复评论。
  • 非回复评论id匹配到评论的parentId,添加到该评论的children列表中。
  • 递归调用。

结果展示:

github 源码

https://github.com/jeremylai7/java-codes/tree/master/basis/src/main/java/recurve

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-06-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码出code 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 评论实体
  • 添加非回复评论
  • 递归添加回复评论
  • 结果展示:
  • github 源码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档